Sure, I can help you with that! Here's a simple script that you can use to create ZFS snapshots and delete them after a specified time on FreeBSD:
#!/bin/sh
# ZFS snapshot and deletion script
# Specify the ZFS filesystem to snapshot
fs="your_zfs_filesystem"
# Specify the snapshot name prefix
snap_prefix="snap_"
# Specify the retention period in days
retention_days=7
# Create a snapshot with a timestamp appended to the name
current_time=$(date +%Y%m%d%H%M%S)
snapshot_name="$snap_prefix$current_time"
zfs snapshot $fs@$snapshot_name
# Delete snapshots older than the retention period
old_snapshots=$(zfs list -t snapshot -o name -H -r $fs | grep "$snap_prefix[0-9]*" | while read snapshot; do
snapshot_time=$(echo $snapshot | awk -F"_" '{print $2}')
age=$(( ($(date +%s) - $(date -jf "%Y%m%d%H%M%S" "$snapshot_time" +%s)) / 86400 ))
if [ $age -gt $retention_days ]; then
echo $snapshot
fi
done)
for snapshot in $old_snapshots; do
zfs destroy $snapshot
done
Here's how the script works:
- Replace
your_zfs_filesystem with the name of the ZFS filesystem you want to snapshot.
- Optionally, change the
snap_prefix variable to specify a different snapshot name prefix.
- Set the
retention_days variable to the number of days you want to retain snapshots before deleting them.
- The script creates a new snapshot with a timestamp appended to the name specified in the
snap_prefix variable.
- The script then lists all snapshots for the specified filesystem that match the
snap_prefix pattern and checks their ages in days.
- If a snapshot is older than the
retention_days value, it is selected for deletion.
- The script then destroys all selected snapshots.
You can schedule this script to run automatically using cron or another scheduling tool. For example, to run the script every day at 2:00 AM, add the following line to your crontab:
0 2 * * * /path/to/zfs-snapshot-script.sh
Replace /path/to/zfs-snapshot-script.sh with the actual path to the script.
Note: Before using this script, make sure you have the zfs utility installed on your FreeBSD system. If it is not already installed, you can install it using the following command:
pkg install zfs