Backup of running VirtualBox machines

If you are using VirtualBox for running servers, you might have stumbled across the question: How do I backup a running virtual machine? The problem is, that the machine state, consisting of the hardware state and especially the virtual harddisk, might change during the backup. This means that you will most probably end up with an inconsistent machine state, from which you might not be able to recover, after restoring the machine from your backup.
So I thought up a little script that creates a static machine state that can be backed up, while the vbox continues to run on a current, changing machine state.
Requirements: two states named current and previous (you have to add them manually first), where “current” is the current vbox snapshot, which the machine is running on. The script will move the current state to the name “previous”, and delete the old “previous” state. It will then take a new “current” snapshot.
The previous snapshot (.vmdk and .sav) together with the main .vmdk or .vdi can then be used for backup purposes.
So it’s a good idea to run this script before your daily backup run. The snapshots take only some seconds. Deleting the old snapshot might take a bit longer, because the deleted machine state is committed back to the main machine state.
Note that your backup software will fail to backup the current snapshot correctly. However, since vbox generates random IDs for the states, it is not easy to exclude the file from the backup set. So just ignore error messages from your backup software concerning that particular state file. This way you will have a machine state that lags only some minutes compared to your backup system.


VBOXMANAGE="/usr/bin/VBoxManage -q"

if [ $# != 1 ]
echo "Usage: $0 VBoxName"

echo "Renaming old snapshot..."
$VBOXMANAGE snapshot "$1" edit previous --name deleteme
echo "Renaming current snapshot..."
$VBOXMANAGE snapshot "$1" edit current --name previous
echo "Taking new snapshot..."
$VBOXMANAGE snapshot "$1" take current
echo "Deleting old snapshot..."
$VBOXMANAGE snapshot "$1" delete deleteme