Here is a bash script to backup all libvirt (kvm) guests on my server. It will iterate over all guests, shutting them down if necessary before copying the image file. After completion the guest is restarted if it was running:
# get a list of all instances
INSTANCES=`virsh -q list --all | awk '{print $2}'`
echo Backup of: ${INSTANCES}
for each in ${INSTANCES} ; do
echo --- ${each}
IS_RUNNING=0
# shutdown if running
if [[ `virsh domstate ${each}` == 'running' ]]; then
IS_RUNNING=1
echo shutting down ${each}
virsh shutdown ${each}
while [[ `virsh domstate ${each}` == 'running' ]]; do
sleep 1
echo waiting for shutdown to complete ${each}
done
fi
sleep 1
# make backup
IMAGEFILE=`virsh dumpxml ${each} | awk '/source file=/{print $2}' | cut -d "'" -f 2`
DESTFILE=/mnt/bigdisk/Backup_virtual_machines/`basename ${IMAGEFILE}`
echo ${each} has image file ${IMAGEFILE} which will be copied to ${DESTFILE}
# rsync -v --progress -a --sparse ${IMAGEFILE} ${DESTFILE}
nice qemu-img convert -p -O qcow2 -o preallocation=metadata ${IMAGEFILE} ${DESTFILE}
# start again if it was running
if (( ${IS_RUNNING} )); then
echo starting ${each}
virsh start ${each}
sleep 20
fi
sleep 1
echo done
done
