Skip to content

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

KVM Tools

Utilities for operating local KVM/libvirt virtual machines.

Automatic KVM Snapshots

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 flock to prevent overlapping runs
  • validates required commands before touching VMs
  • quotes all virsh arguments
  • 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

Requirements

  • Bash
  • virsh from libvirt
  • flock
  • permissions to list VMs and manage snapshots for the target libvirt connection

Configuration

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

Usage

Run the script directly:

./scripts/automatic-kvm-snapshots.sh

Example cron entry for hourly snapshots:

0 * * * * /path/to/kvm-tools/scripts/automatic-kvm-snapshots.sh

Example with a custom retention count:

0 2 * * * RETENTION=7 /path/to/kvm-tools/scripts/automatic-kvm-snapshots.sh

Testing

The test harness uses fake virsh and date commands, so it can run without libvirt installed:

bash tests/automatic-kvm-snapshots-test.sh

Static 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

About

Various tools to simplify life of the KVM admin

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages