In this lesson, you will learn how to prevent your disk from filling up by implementing automated pruning policies for your Btrfs snapshots.
The Retention Problem
As you have learned, taking snapshots is incredibly efficient thanks to Copy-on-Write. However, if you take daily snapshots and never delete them, your disk will eventually run out of space. Managing these manually is prone to human error, which is why we implement retention policies. A common strategy is the "Grandfather-Father-Son" approach: keeping daily snapshots for a week and weekly snapshots for a month.
Automated Pruning Logic
Pruning is the process of identifying snapshots that have exceeded their "shelf life" and removing them. While you could write a custom shell script to check file creation dates using btrfs subvolume list, it is standard practice to use a naming convention that allows for easy filtering.
For example, if you name your snapshots backup-daily-2023-10-27 and backup-weekly-2023-10-01, you can use a simple loop in a cron job to keep your storage tidy.
Implementing a Basic Policy
To prune snapshots older than 7 days, you can execute a logic flow like this:
# List snapshots in a specific directory
# Filter by a pattern, compare dates, and delete if old
for subvol in /snapshots/daily/*; do
# Check if the subvolume is older than 7 days
if [ $(find "$subvol" -mtime +7) ]; then
btrfs subvolume delete "$subvol"
fi
done
By running this script as a cron job daily, you ensure that your snapshot directory remains a sliding window of the last week’s history.
Best Practices
- Naming conventions: Always include the frequency (e.g.,
-daily-) in the name. This prevents your script from accidentally deleting a manual snapshot you wanted to keep. - Safety checks: Before running a
deletecommand in a script, always test the logic by replacingbtrfs subvolume deletewithechoto verify exactly which snapshots will be removed. - External storage: Remember that snapshots reside on the same filesystem. Pruning is essential for health, but if you need long-term archives, use the
btrfs sendcommand to transfer those snapshots to an external pool instead of keeping them local forever.
Key Takeaway: Automated retention policies use consistent naming conventions and periodic cleanup scripts to ensure your disk space is reclaimed from outdated snapshots without manual intervention.