Skip to content

Instantly share code, notes, and snippets.

@ianb-mp
Created March 3, 2024 23:33
Show Gist options
  • Save ianb-mp/a518dc538a0fd652bd0c5490abb55fc7 to your computer and use it in GitHub Desktop.
Save ianb-mp/a518dc538a0fd652bd0c5490abb55fc7 to your computer and use it in GitHub Desktop.
Cleanup libvirt snapshots
#!/bin/bash
set -e
DRYRUN=true
[ $# -lt 2 ] && echo "Usage: $0 <domain> <keep>" && exit 1
DOMAIN=$1
KEEP=$2
SNAPSHOTS=$(virsh snapshot-list ${DOMAIN} --name | grep -v '^$' | sort -n)
COUNT=$(echo "$SNAPSHOTS" | wc -l)
if [ "$COUNT" -gt $KEEP ]; then
OLD=$(echo "$SNAPSHOTS" | tail +$((KEEP+1)))
for s in $OLD; do
echo "Removing ${DOMAIN} snapshot '$s'" | logger
if [ "$DRYRUN" == false ]; then
virsh snapshot-delete $DOMAIN $s
fi
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment