Backing up your VMs

Here’s the problem; you have several virtual machines running on your VMWare server. Each one is configured to back up some of its important state, but what about the machine itself?

Here’s a shell script I wrote to handle the situation.

  1.  
  2. #!/bin/sh
  3.  
  4. BACKUPDIR=/mnt/bignasdrive/vms
  5.  
  6. function backupvm
  7. {
  8.   vm_config=$1
  9.   vm_path=`dirname "$vm_config"`
  10.   targetdir=$BACKUPDIR$vm_path
  11.  
  12.   echo "Copying $vm_path to $targetdir"
  13.   mkdir –parents $targetdir
  14.   cp –update –verbose $vm_path/* $targetdir/
  15. }
  16.  
  17. function suspendvm
  18. {
  19.   vm_config=$1
  20.  
  21.   echo Suspending  $vm_config…
  22.   vmware-cmd "$vm_config" suspend trysoft
  23. }
  24.  
  25. function resumevm
  26. {
  27.   vm_config=$1
  28.  
  29.   echo Resuming $vm_config…
  30.   vmware-cmd "$vm_config" start trysoft
  31. }
  32.  
  33. function checkbackupvm
  34. {
  35.   vmpath=$1
  36.   vmstate=$2
  37.   state=`echo $vmstate|awk ‘{print $NF}’`
  38.   if [ "$state" == "on" ]; then
  39.     suspendvm "$vmpath"
  40.     backupvm "$vmpath"
  41.     resumevm "$vmpath"
  42.   else
  43.     backupvm "$vmpath"
  44.   fi
  45. }
  46.  
  47. function getvmlist
  48. {
  49.   for b in ${VMs// /___} ;
  50.   do
  51.     vmstate=`vmware-cmd "${b//___/ }" getstate`
  52.     checkbackupvm "${b//___/ }" "$vmstate"
  53.   done
  54. }
  55.  
  56. VMs=`vmware-cmd -l`
  57.  
  58. getvmlist
  59.  

What the script does is
* Get the list of registered machines
* For each machine,
* if it’s running – suspend, backup, restore
* else backup

Much ofthe time was spent handling the completely silly idea of putting spaces in file names.

Note that you must probably change the backup target directory high up in the script. I mounted my ReadNAS+ with 1.5TB space for backups…

Put the script somewhere, make it runnable and symlink it into /etc/cron.daily or cron.weekly

chmod +x backupvms
ln -s backupvms /etc/cron.daily

It is worth noting that I ran into problems as not all services on all machines handled the suspend/restore cycle well. The backing up worked just fine, though :)

–Jesper Högström

  • Share/Bookmark

Leave a comment

Your comment