Wednesday, September 14, 2011

Start VirtualBox machines automatically

VirtualBox is a nice way to run various virtual machines. Although it's mainly meant to be used interactively, using PhpVirtualBox it can even be used headless. Great for running a few isolated virtualmachines on a headless machine without having to remember the VBoxManage commandline options.
However, when a machine is rebooted, the state of the virtualmachines is lost (ie. which one is powered of and which one is powered on). To remedy this, I use a small shell-script that runs as part of the machine bootup sequence to revitalize all paused virtualmachines that are marked as autostart. VirtualBox has the option to attach 'extradata' to each virtual machine which are just basic key-value pairs. I mark all auto-start virtual machines as follows:

vboxmanage setextradata XYZ autostart true

Where XYZ is the machine name. Unfortunately the property cannot be set using the web-ui. But as this is one-time command, it's not that big of an issue.
Next the virtual machines are booted manually (using the web-ui or otherwise) to run headless. Next when the host goes down orderly, a shell-script runs pausing all virtual machines marked as autostart=true. When the machine starts up, all virtual machines marked as autostart will be resumed.

The basic script I use is this:


#!/bin/bash
USER=marcel
VBOXMNG=vboxmanage
CMD="$1"
start_stop()
{
for f in `su -l -c "${VBOXMNG} list vms" ${USER}`
do
        if [ "${f:0:1}" == "{" ]
        then
                if [ "`su -l -c "${VBOXMNG} getextradata ${f} autostart" ${USER}`" == "Value: true" ]
                then
if [ "${CMD}" == "start" ]
then
echo Resuming ${f}
su -l -c "${VBOXMNG} controlvm ${f} resume" ${USER}
else
echo Pausing ${f}
su -l -c "${VBOXMNG} controlvm ${f} pause" ${USER}
fi
                fi
        fi
done
}
case $CMD in
start)
start_stop
;;
stop)
start_stop
;;
*)
echo Only stop or start is supported
exit 1
esac
Just put this in the init.d directory and use "update-rc.d startvms 99" to setup the script.


No comments:

Post a Comment