Last active
April 14, 2021 21:09
-
-
Save gfnord/8bd45ee3e0340a10bbbb4e797bb79d0f to your computer and use it in GitHub Desktop.
XCP-NG/Xenserver/Xen VM backup bash script
This file contains hidden or 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 | |
TARGET=$1 | |
BACKUP_LOCATION=/backup/XVA | |
VMS_LIST=/tmp/.vms_list_000 | |
if [ -z "$1" ]; then | |
echo "No vmname found" | |
echo "Usage: ./backup_vm.sh VMNAME" | |
exit 0 | |
fi | |
# Function to list all vms with UUIDs in one line each | |
list_all_vms() { | |
UUIDFILE=/tmp/xen-uuids.txt | |
VMS_LIST=/tmp/.vms_list_000 | |
rm -f ${VMS_LIST} | |
xe vm-list is-control-domain=false is-a-snapshot=false | grep uuid | cut -d":" -f2 > ${UUIDFILE} | |
for VMUUID in $(cat ${UUIDFILE}); do | |
VMNAME=`xe vm-list uuid=$VMUUID | grep name-label | cut -d":" -f2 | sed 's/^ *//g'` | |
echo "$VMNAME - UUID:$VMUUID" >> ${VMS_LIST} | |
done | |
} | |
list_all_vms | |
LINE=`cat ${VMS_LIST}|grep $TARGET` | |
NL=' | |
' | |
# Check if the LINE contains only one line, which means we matched the target vm | |
case $LINE in | |
*"$NL"*) echo "Refine vmname, more than one found"; exit 0;; | |
esac | |
NAME=`echo $LINE|awk '{print $1}'` | |
UUID=`echo $LINE|cut -d ":" -f2` | |
echo "Taking a snapshot of VM $NAME" | |
SNAP_UUID=`xe vm-snapshot uuid=$UUID new-name-label=$NAME-snapshot` | |
echo "Done: SNAP UUID: $SNAP_UUID" | |
xe template-param-set is-a-template=false ha-always-run=false uuid=$SNAP_UUID | |
echo "Exporting the backup to file $NAME-backup.xva" | |
xe vm-export vm=$SNAP_UUID filename=$BACKUP_LOCATION/$NAME-backup.xva | |
echo "Removing the snapshot" | |
xe vm-uninstall uuid=$SNAP_UUID force=true | |
echo "Zipping backup file" | |
gzip $BACKUP_LOCATION/$NAME-backup.xva | |
echo "Done. Backup completed." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment