You will obviously need to adapt to your setup. Possibly you either want to add zfs package to the system units path or use lib.getExe instead, I did just not yet bother to change it.
You obviously need to change the after/requires and i am not 100% sure that those are totally correct or if there is a more generic one in the meantime.
It works on my machine (or at least i did not notice any issue since migration to systemd initrd long time ago, i enabled it before it became default).
I had no idea on how I should go about this, but at least now I have somewhere to start. I will take this and adapt it to my setup, and will report the result here for reference.
You can use nixos-rebuild build-vm to create an equivalent VM and test that. It’s going to be a little more tricky to make a testable encrypted root device for that, though.
I have NixOS devices with impermanence setup that only needs rolling back the ZFS root pool. Those work fine with this:
boot.initrd.systemd.services.zfs-rollback = {
description = "Rollback ZFS root dataset to blank snapshot";
wantedBy = [
"initrd.target"
];
after = [
# This is a dynamically generated service, based on the zpool name
"zfs-import-${ZPOOL_NAME}.service"
];
before = [
"sysroot.mount"
];
path = [ pkgs.zfs ];
unitConfig.DefaultDependencies = "no";
serviceConfig.Type = "oneshot";
script = ''
zfs rollback -r ${DATASET_NAME}@blank
'';
};
But for my main device I have the following setup:
Root ZFS pool on SSD encrypted via passphrase.
Secondary ZFS pool on HDD encrypted by a key inside a file.
The file is stored on the SSD.
Once I enter the passphrase to unlock the SSD, the HDD key should automatically be loaded such that I don’t get an extra password prompt on each boot.
With scripted stage 1, I achieved what I want with this config:
# Rollback to Empty Root On Boot
boot.initrd.postResumeCommands = lib.mkAfter ''
zfs rollback -r zssd/enc/root@blank
zfs mount zssd/enc/hdd-key
zfs load-key zhdd/enc
zfs unmount /hdd-key
'';
This is not as straightforward to migrate to SystemD stage 1. When I do the migration and reboot, loading the key fails, but it prevents booting so I can’t inspect or debug anything.