ZFS Dataset Snapshot Rotation with Retention Policies
This snippet implements a snapshot rotation script for ZFS datasets on Proxmox, leveraging the zfs snapshot and zfs destroy commands. The script calculates a timestamped snapshot name and retains the last N snapshots per dataset, using a for loop to enumerate and prune older snapshots. It operates at the dataset level, allowing granular control over VMs, containers, or storage pools. The script uses the zfs list -H -o name -t snapshot command to gather existing snapshots, sorts them by creation time, and removes those exceeding the retention threshold. This approach ensures a rolling backup window without manual intervention, preserving storage space and maintaining a consistent recovery point objective.
In production, this script is ideal for environments with frequent VM or CT backups, such as CI/CD pipelines, database servers, or critical application hosts. It can be scheduled via cron or systemd timers to run hourly or daily, capturing point-in-time states before updates or configuration changes. The script is particularly useful for Proxmox clusters where snapshots are used for rollback during patching or testing, ensuring that only recent states are retained to avoid storage exhaustion.
Security implications include ensuring the script runs with sufficient privileges, typically root, and that snapshot names are sanitized to prevent injection if dataset names are user-controlled. Performance impact is minimal, as snapshot creation is near-instantaneous, but pruning many old snapshots can generate I/O. Common pitfalls include not handling datasets with spaces or special characters, and missing the -r flag for recursive snapshots, which can leave child datasets unprotected. Always test with a dry-run by setting RETENTION to a high value first.
> System.Execute()
#!/bin/bash
# Snapshot rotation for ZFS datasets on Proxmox
RETENTION=5
DATASETS=("rpool/data" "rpool/vmdata")
for ds in "${DATASETS[@]}"; do
SNAP_NAME="${ds}@auto_$(date +%Y%m%d_%H%M%S)"
zfs snapshot "$SNAP_NAME"
# List existing snapshots, sort, and remove older ones
zfs list -H -o name -t snapshot -s creation "$ds" | head -n -$RETENTION | while read -r snap; do
zfs destroy "$snap"
done
done
> Architecture & Security Context
Verified for Valters IT Hub. When deploying this configuration in a production homelab or enterprise environment, ensure that you monitor system resources and implement strict access controls. Administrator privileges are required.
ID: VALTERSIT-4F74C70CB3EF