Created
January 15, 2017 06:05
-
-
Save oscarkuo/8a09948d1c6bb40c955ac1076b9879e9 to your computer and use it in GitHub Desktop.
Backup KVM virtual machine hard disk images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
VMPATHS=() | |
VMNAMES=() | |
VMCONFS=() | |
SSPATHS=() | |
TGZNAME=/srv/backups/vmbackup-`date '+%y%m%d-%H%M%S'`.tar.gz | |
TGZLINK=/srv/backups/vmbackup-current.tar.gz | |
cleanup() { | |
for vm in ${VMNAMES[*]} | |
do | |
echo blockcommit snapshot for VM \"$vm\" | |
virsh blockcommit $vm vda --active --pivot --shallow --verbose | |
done | |
echo deleting snapshots and config files | |
rm -f ${SSPATHS[*]} ${VMCONFS[*]} | |
} | |
trap cleanup EXIT | |
for vm in $@ | |
do | |
VMNAME=$vm | |
VMPATH=/var/lib/libvirt/images/$VMNAME.qcow2 | |
VMCONF=/tmp/$VMNAME.xml | |
BKNAME=$VMNAME-`date '+%y%m%d-%H%M%S'` | |
SSPATH=/srv/snapshots/$BKNAME.qcow2 | |
VMNAMES+=($VMNAME) | |
VMPATHS+=($VMPATH) | |
echo saving snapshot xml $VMCONF | |
virsh dumpxml $VMNAME > $VMCONF | |
VMCONFS+=($VMCONF) | |
echo creating snapshot for VM \"$VMNAME\" to \"$VMPATH\" | |
virsh snapshot-create-as --domain $vm $BKNAME --diskspec vda,file=$SSPATH --disk-only --atomic --no-metadata | |
SSPATHS+=($SSPATH) | |
done | |
tar cf - ${VMPATHS[*]} ${VMCONFS[*]} | pigz -p 3 > $TGZNAME | |
rm -f $TGZLINK | |
# only keep most recent 3 backups | |
ls -tp | grep -v '/$' | tail -n +4 | xargs -d '\n' rm -- | |
# relink the current backup | |
ln -s $TGZNAME $TGZLINK |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check https://github.com/abbbi/virtnbdbackup for an alternative approach.