Friday, June 26, 2009

Backing up VMWare ESX 3.5

I'd been whining about the troubles I had getting the various parts of a VMWare backup script working. Well, I've got something that appears to fill the bill.

The end result is that I have a backup local to the host, so I can restore very quickly, and as many past snapshots as my Windows server can hold.

The first thing you need to do is open up the firewall:
esxcfg-firewall --enableService smbClient

Note that in order for everything to work, I have to use the FQDN to the server. Otherwise, I'd get an error regarding broadcasts.

Here's the main script:
#!/bin/sh

VMCONFIGLIST=`/usr/bin/vmware-cmd -l`
TODAY=`date +%Y%m%d`
BACKUPBASE=/vmfs/volumes/`hostname`\:raid0/backups

USER=root
PASSWORD=nunyabidnz

WINUSER=NA/meh
WINPW=blah
WINDEST='//server01.example.com/backups'

if [ ! -d ${BACKUPBASE} ]
then
echo "Backup directory ${BACKUPBASE} does not exist."
echo "Exiting"
# no, I don't want to create it. If there's a problem with the path,
# there's no telling where these backups will end up.
exit
fi

echo "Back up for ${TODAY}"
echo "Backup directory ${BACKUPBASE}"

for VM in ${VMCONFIGLIST}
do
# set up the variables for this loop
VMDIR=`dirname ${VM}`
echo "Looking for ${VMNAME} in ${VMDIR}"

# if the config file doesn't exist, we can't do anything
if [ ! -f ${VM} ]
then
echo " * Did not find ${VM}."
echo " * Skipping"
continue
fi

# get the VM name from the config file
VMNAME=`cat ${VM} | awk '/displayName =/ {print $3}' | sed 's/\"//g'`

DESTDIR=${BACKUPBASE}/${VMNAME}

TARNAME=${VMNAME}.${TODAY}.tgz

# the work begins here
# all the configurable stuff should be above this line

echo " - Backing up ${VMNAME}"
echo " - file ${VM}"

# vcbMounter bombs out if the directory already exists
if [ -d ${DESTDIR} ]
then
echo " - deleting directory ${DESTDIR}"
rm -Rf ${DESTDIR}
fi

# create the backup
echo " - Starting vcb..."
/usr/sbin/vcbMounter -h `hostname` -t fullvm -u ${USER} -p ${PASSWORD} -r ${DESTDIR} -a Name:${VMNAME}

# check vcbMounter's return
if [ "$?" -ne "0" ]
then
echo " - Error backing up VM ${VMNAME}"
continue
else
echo " - Successful backup of ${VMNAME}"
fi

# compress it

echo " - Archiving backup to tarfile ${BACKUPBASE}/${TARNAME}"
echo " - to tarfile $TARNAME"
# --force-local to ignore the ":" in the path
tar -C ${BACKUPBASE} --force-local -czf ${BACKUPBASE}/${TARNAME} ${DESTDIR}
echo " - Compression completed"

echo " - Copying to ${WINDEST}"
/usr/bin/smbclient -c "prompt off; put ${BACKUPBASE}/${TARNAME} ${TARNAME}" -U ${WINUSER} ${WINDEST} ${WINPW}

echo "Cleaning up .tgz"
rm -f ${BACKUPBASE}/${TARNAME}

echo " --- ${VMNAME} complete --- "
done

Any suggestions for improvements (how about an occasional function , Mr. Goon? Or check the return from smbclient? Hmmm?) are welcome.

No comments:

Post a Comment