Utilities for operating local KVM/libvirt virtual machines.
scripts/automatic-kvm-snapshots.sh creates timestamped libvirt snapshots for a fixed whitelist of VMs and prunes old snapshots after a new snapshot has been created and verified.
The script is intended for unattended runs from cron or systemd timers. It is defensive by default:
- runs with strict Bash settings
- uses
flockto prevent overlapping runs - validates required commands before touching VMs
- quotes all
virsharguments - creates and verifies the new snapshot before pruning old cron snapshots
- keeps processing other whitelisted VMs when one VM fails
- exits nonzero when any VM snapshot operation fails
- Bash
virshfrom libvirtflock- permissions to list VMs and manage snapshots for the target libvirt connection
The VM whitelist is currently defined in the script:
readonly -a VM_BACKUP_WHITELIST=("AlmaLinux-VM1" "AlmaLinux-VM2")Runtime behavior can be adjusted with environment variables:
| Variable | Default | Description |
|---|---|---|
RETENTION |
3 |
Number of cronjob_ snapshots to keep per VM. |
SNAPSHOT_PREFIX |
cronjob_ |
Prefix used to identify snapshots managed by this script. |
LOCK_FILE |
/run/lock/automatic-kvm-snapshots.lock |
Lock file used by flock. |
VIRSH_BIN |
virsh |
Path or command name for virsh. |
FLOCK_BIN |
flock |
Path or command name for flock. |
DATE_BIN |
date |
Path or command name for date. |
Snapshot names use the UTC format:
cronjob_YYYY_MM_DD_HHMMSSZ
Run the script directly:
./scripts/automatic-kvm-snapshots.shExample cron entry for hourly snapshots:
0 * * * * /path/to/kvm-tools/scripts/automatic-kvm-snapshots.shExample with a custom retention count:
0 2 * * * RETENTION=7 /path/to/kvm-tools/scripts/automatic-kvm-snapshots.shThe test harness uses fake virsh and date commands, so it can run without libvirt installed:
bash tests/automatic-kvm-snapshots-test.shStatic checks:
shellcheck scripts/automatic-kvm-snapshots.sh tests/automatic-kvm-snapshots-test.sh
bash -n scripts/automatic-kvm-snapshots.sh tests/automatic-kvm-snapshots-test.sh