How can I automatically unlock and mount a ZFS pool at boot?
I was wondering if it’s possible to automatically decrypt and mount a ZFS pool and its datasets at boot. Currently, I have to unlock the pool manually by using the command # zfs load-key -a
and then run # zfs mount -a
. It might also be worth mentioning that the "key", at the moment, is a passphrase (maybe it would be better to convert it to a keyfile and store it somewhere on the system?).
I’m running Ubuntu Server 23.04
I found out how to do this myself.
- First of all, after you’ve loaded the keys using
# zfs load-key -L file:///path/to/keyfile <pool>
, the key will stay loaded unless you explicitly unload it using# zfs unload-key
. - In case you want to try to automatically load the key anyway, below’ss a quick systemd service I’ve written, but be warned: the service will fail unless you unload the keys before rebooting.
# /etc/systemd/system/zfs-load-key.service
[Unit]
Description=Load encryption keys
DefaultDependencies=no
Before=zfs-mount.service
After=zfs-import.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/zfs load-key -L file:///etc/zfs/zpool.key <pool-name>
[Install]
WantedBy=zfs-mount.service
- There are a couple of ways to automatically mount the pool(s) at boot:
- Option #1: Using
zfs-mount.service
sudo zpool set cachefile=/etc/zfs/zpool.cache <pool-name>
sudo systemctl enable --now zfs-import-cache.service
sudo systemctl enable --now zfs.target
sudo systemctl enable --now zfs-import.target
sudo systemctl enable --now zfs-mount.service
- Option #2: Using
zfs-mount-generator
sudo mkdir -p /etc/zfs/zfs-list.cache
sudo systemctl enable --now zfs.target
sudo systemctl enable --now zfs-zed.service
sudo touch /etc/zfs/zfs-list.cache/<pool-name>
cat /etc/zfs/zfs-list.cache/<pool-name> # if the file is empty, check that zfs-zed.service is running; if it is, run the command below
sudo zfs set canmount=off <pool-name>
cat /etc/zfs/zfs-list.cache/<pool-name> # if the file has been updated, run the command below
sudo zfs set canmount=on <pool-name>
# A file needs to be (manually) created in `/etc/zfs/zfs-list.cache` for each ZFS pool in your system and ensure the pools are imported by enabling `zfs-import-cache.service` and `zfs-import.target`.