--- title: "ZFS Automatic Snapshotting" date: 2022-10-31T17:56:35Z tags: ["archlinux", "linux", "zfs"] draft: true icon: backup --- ## Goal ## Solution ### Creating snapshots {{< codegroup >}} Systemd-timer ``` [Unit] Description=Create a daily ZFS snapshot for %I [Timer] OnCalendar=daily Persistent=true [Install] WantedBy=timers.target ``` --- Systemd-service ``` [Unit] Description=Create a ZFS snapshot for %I DefaultDependencies=no [Service] Type=oneshot RemainAfterExit=yes ExecStart=/usr/bin/bash -c '/usr/bin/zfs snapshot "%I@daily-$(date "+%%Y-%%m-%%d")"' ``` {{< /codegroup >}} ### Cleaning up snapshots Get all older snapshots {{< codegroup >}} bash ``` zfs list -t snapshot -o name | \ perl -e ' my $one_week_ago = `date --date "7 days ago" "+%s"`; my %snapshots = (); for (<>) { if (my ($dataset, $snapshot, $date) = /([\w\/]+)@(daily-(\d+\-\d+\-\d+))/) { if (`date --date "$date" "+%s"` < $one_week_ago) { push(@{$snapshots{$dataset}}, $snapshot); } } } while(my ($key, $value) = each %snapshots) { print "$key@", join(",", @{$value}), "\n"; }' ``` {{< /codegroup >}}