Automatically Create, Rotate and Destroy Periodic ZFS Snapshots

The main reason for moving my home directories to a ZFS file system is ZFS’s support for snapshots. I have found them quite handy on server systems when something has been accidentally deleted, a software upgrade has failed, or software has not done what it promised. A simple rollback to a previous state can help undo changes and allow you to continue safely. ZFS-Auto-Snapshot is a tool that uses cron to automatically create, rotate and destroy snapshots in the background.

How To Do

Install the zfs-auto-snapshot package

sudo apt install zfs-auto-snapshot

On Ubuntu and Debian, cron scripts are already in place to trigger the script.

Enabling or disabling automatic snapshots for a specific ZFS is done via ZFS properties. This property is inherited by all descendant datasets, so there is no need to set it manually for each one.

sudo zfs set com.sun:auto-snapshot=true zhome/home

You should also specify where you don’t want to see snapshots.

sudo zfs set com.sun:auto-snapshot=false zhome/home/tstusr1
sudo zfs set com.sun:auto-snapshot=false zhome/home/tstusr2

You can enable or disable frequent (every 15 minutes), hourly, daily, weekly or monthly snapshots. They are all enabled by default, so the first snapshot should appear soon.

zfs set com.sun:auto-snapshot:frequent=false zhome/home/tstusr
zfs set com.sun:auto-snapshot:daily=true ...
zfs set com.sun:auto-snapshot:monthly=true ...
...

The following commands are helpful for listing, creating and destroying snapshots:

zfs list -t snapshot

zfs snapshot -r zpool/foo/bar@name

zfs destroy zpool/foo/bar@name

To restore to a certain snapshot, ZFS will roll back all the files and delete all the newer snapshots, so be careful!

zfs rollback zpool/foo/bar@name -r

ZFS itself does not support deleting large numbers of snapshots, but this command comes in handy for that purpose.

sudo zfs list -H -o name -t snapshot zhome/somedir | xargs -n1 zfs destroy

ZFS rollbacks are permanent. They recover everything from the snapshot. If you only want to recover some files or directories, ZFS does not support this directly. However, there is a workaround: Clone the snapshot to a different location and mount the clone. Restore the required files and then delete the clone.

sudo zfs clone zhome/home/ebablick@zfs-auto-snap_frequent-2025-08-25-1845 \
         -o mountpoint=/mnt zhome/ebablick_clone_of_snapshot_2025-08-25-1845

copy /mnt/... /to/...

sudo zfs destroy zhome/ebablick_clone_of_snapshot_2025-08-25-1845 -r

Take a look at the zfs-auto-snapshot(8) manual page. The tool itself offers a few interesting options for executing pre- and post-snapshot commands. The number of snapshots to keep can also be configured via command line arguments, which then need to be adapted for the cron jobs.