ZFS & Nixos Badness
I’ve recently had to write a config for a multi-user system. I was too lazy to write the explicit config and came up with this masterpiece to get the thing going. Thought I’d share this terrible snippet. It creates a home dataset per user on the pool and ensures it’s mounted. There’s probably better ways to do this but for now this will do.
{ lib, pkgs, ... }:
let
users = [
{
username = "user";
... # Other user details
}
... # Other users
];
usersWithDatasets = map (
user:
let
username = user.username;
in
{
inherit username;
dataset = "zpool/home/${username}";
mount = "/home/${username}";
}
) users;
zfsCreateUserDatasets = pkgs.writeScriptBin "zfs-user-datasets" ''
#!${pkgs.python312}/bin/python3
import subprocess
import pwd
import os
import json
users = json.loads('${builtins.toJSON usersWithDatasets}')
for u in users:
ds = u["dataset"]
mp = u["mount"]
# Create dataset if missing
try:
subprocess.run(
["${pkgs.zfs}/bin/zfs", "list", ds],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except subprocess.CalledProcessError:
print(f"Creating ZFS dataset {ds}")
subprocess.run(
["${pkgs.zfs}/bin/zfs", "create",
"-o", "mountpoint=legacy",
"-o", "quota=150G",
ds],
check=True,
)
# Ensure mountpoint exists
pw = pwd.getpwnam(u["username"])
os.chown(mp, pw.pw_uid, pw.pw_gid)
os.makedirs(mp, exist_ok=True)
os.chmod(mp, 0o700)
'';
in
{
environment.systemPackages = with pkgs; [
python312
zfsCreateUserDatasets
];
users.users = builtins.listToAttrs (
map (u: {
name = u.username;
value = {
isNormalUser = true;
home = "/home/${u.username}";
createHome = false; # Service will create and mount these dirs
};
}) usersWithDatasets
);
systemd.services.zfs-user-datasets = {
description = "Create ZFS datasets for users";
wantedBy = [ "multi-user.target" ];
after = [
"zfs-import.target"
"zfs-mount.service"
];
wants = [ "zfs-import.target" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${zfsCreateUserDatasets}/bin/zfs-user-datasets";
RemainAfterExit = true;
};
};
fileSystems = lib.listToAttrs (
map (u: {
name = "/home/${u.username}";
value = {
device = "zpool/home/${u.username}";
fsType = "zfs";
options = [ "defaults" ];
};
}) usersList
);
}