XenServer VM Backup to NFS Script

The following script creates a snapshot of a VM, then exports it to an NFS share for backup or disaster recovery purposes.

Schedule this via cron on a host server.  Update the NFSSERVER and NFSSHARE variables to match your NFS configuration.

#!/bin/bash
 
DATE=`date +%d%B%y`
XSNAME=`echo $HOSTNAME`
VMUUIDFILE=/tmp/vmuuids.txt
BACKUPBASE=/mnt/backup
NFSSERVER=10.10.41.22
NFSSHARE=/stage/xenserver
POOL=`xe pool-list | grep name-label | cut -d":" -f2 | xargs`
BACKUPPATH=$BACKUPBASE/$POOL
HOSTUUID=`xe host-list name-label=$XSNAME | grep uuid | cut -d":" -f2 | xargs`
 
mkdir -p $BACKUPBASE
mount -t nfs $NFSSERVER:$NFSSHARE $BACKUPBASE
mkdir -p $BACKUPPATH
 
xe vm-list is-control-domain=false is-a-snapshot=false resident-on=$HOSTUUID | grep uuid | cut -d":" -f2 > $VMUUIDFILE
 
while read VMUUID
do
	# Get the VM Name
	VMNAME=`xe vm-list uuid=$VMUUID | grep name-label | cut -d":" -f2 | sed 's/^ *//g'`
	# Create a snapshot and save the snapshot UUID
	SNAPUUID=`xe vm-snapshot uuid=$VMUUID new-name-label="SNAPSHOT-$VMUUID-$DATE"`
	# Set flags on the snapshot
	xe template-param-set is-a-template=false ha-always-run=false uuid=$SNAPUUID
	# Export the snapshot
	xe vm-export vm=$SNAPUUID filename="$BACKUPPATH/$VMNAME.xva"
	# Delete the snapshot - TODO: Check if VDIs exist afterwards
	xe snapshot-uninstall snapshot-uuid=$SNAPUUID force=true
	# Compress the backup
	tar -czf $BACKUPPATH/$VMNAME.tar.gz $BACKUPPATH/$VMNAME.xva
	# Remove uncompressed backup
	rm -f $BACKUPPATH/$VMNAME.xva
 
done < $VMUUIDFILE
 
umount /mnt/backup

Leave a Reply

Your email address will not be published. Required fields are marked *