Linux – Start VirtualBox Headless VM On Boot

bootlinuxUbuntuvirtualbox

I am running two VirtualBox headless VMs on an Ubuntu 12.04 host. I would like these VMs to start automatically when the system boots.

I have two crontab entries set like this (under the user which owns the VMs):

@reboot /usr/bin/vboxheadless -startvm io
@reboot /usr/bin/vboxheadless -startvm pbx

But it seems that doesn't do the trick. If I run the command directly from the terminal, the machines start up without a hitch, but I can't seem to get them to start once the system starts. I'm thinking maybe the crontab is running before the VirtualBox program/library is loaded.

How do I start these VMs automatically?

Best Answer

This is what I use. It starts the VMs on boot and saves their state on shutdown/reboot

#!/bin/bash
### BEGIN INIT INFO
# Provides:       vmboot
# Required-Start: vboxdrv
# Required-Stop:
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Short-Description: Stop/Start VMs on System shutdown
### END INIT INFO

VBOXUSER=vboxuser
SU="sudo -H -u $VBOXUSER"
VBOXMANAGE=/usr/bin/VBoxManage
VBOXHEADLESS=/usr/bin/VBoxHeadless
RUNNINGVMS=$($SU $VBOXMANAGE --nologo list runningvms | sed -e 's/^".*".*{\(.*\)}/\1/')
ALLVMS=$($SU $VBOXMANAGE --nologo list vms | sed -e 's/^".*".*{\(.*\)}/\1/')

case $1 in
stop)
if [[ -n $RUNNINGVMS ]]; then
echo "Saving the state of all running VMs..."
for v in $RUNNINGVMS; do
    $SU $VBOXMANAGE --nologo controlvm $v savestate
done
fi
;;
start)
for v in $ALLVMS; do
if [[ -n $($SU $VBOXMANAGE --nologo showvminfo $v | grep saved) ]]; then
    echo "Restoring VMs..." && $SU $VBOXHEADLESS -s $v & > /dev/null
fi
done
;;
*)
echo "Usage: /etc/init.d/vmboot start | stop"; exit 1
;;
esac
exit 0

Just save it in /etc/init.d. I named mine vbox. Run update-rc.d <script name> defaults and you should be good to go.

Related Question