From 79d5469aa51bab5a301ee993a28c65d2011a2cb1 Mon Sep 17 00:00:00 2001 From: Daniel_I_Am Date: Mon, 31 Oct 2022 17:51:30 +0000 Subject: [PATCH] Add first draft of ZFS auto-snaptshot code --- content/snippets/zfs-automatic-snapshots.md | 61 +++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 content/snippets/zfs-automatic-snapshots.md diff --git a/content/snippets/zfs-automatic-snapshots.md b/content/snippets/zfs-automatic-snapshots.md new file mode 100644 index 0000000..9e398a3 --- /dev/null +++ b/content/snippets/zfs-automatic-snapshots.md @@ -0,0 +1,61 @@ +--- +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 >}}