2

I have an Ubuntu server on which a Virtualbox virtual machine needs to be running at all times. The VMs are administered by a specific user VMAdmin which has no admin privileges. I need to create a init.d script for handling my virtualbox VMs.
It should:

  • start VM whenever the host system boots;
  • save the guest system's state whenever the host is shut down;
  • provide commands for starting, shutting down, resetting and backing up the VM.
digitxp
  • 14,884

1 Answers1

8

The following script takes care of all of the above:

#! /bin/sh
# /etc/init.d/vbox

#Edit these variables!
VMUSER=VMAdmin
VMNAME="cdb62186-7c30-4c25-a0b0-e4a32cfb0504"
BASEFOLDER=/home/VMAdmin/path/to/backups/

case "$1" in
    start)
        echo "Starting VirtualBox VM..."
        sudo -H -u $VMUSER VBoxManage startvm "$VMNAME" --type headless
        ;;
    reset)
        echo "Resetting VirtualBox VM..."
        sudo -H -u $VMUSER VBoxManage controlvm "$VMNAME" reset
        ;;
    stop)
        echo "Saving state of Virtualbox VM..."
        sudo -H -u $VMUSER VBoxManage controlvm "$VMNAME" savestate
        ;;
    shutdown)
        echo "Shutting down Virtualbox VM..."
        sudo -H -u $VMUSER VBoxManage controlvm "$VMNAME" acpipowerbutton
        ;;
    status)
        sudo -H -u $VMUSER VBoxManage list vms -l | grep -e ^"$VMNAME": -e ^State | sed s/\ \ //g | cut -d: -f2-
        ;;
    backup)
        echo ""
        sudo -H -u $VMUSER VBoxManage controlvm "$VMNAME" acpipowerbutton

        echo "Waiting for VM "$VMNAME" to poweroff..."
        until $(sudo -H -u $VMUSER VBoxManage showvminfo --machinereadable "$VMNAME" | grep -q ^VMState=.poweroff.)
        do
          sleep 1
        done

        FILENAME=$(date +"%Y_%m_%d-%T")
        echo "Backing up Virtualbox VM to '$BASEFOLDER$FILENAME'..."
        sudo -H -u $VMUSER VBoxManage clonevm "$VMNAME" --options keepallmacs --name $FILENAME --basefolder $BASEFOLDER

        echo "Restarting VirtualBox VM..."
        sudo -H -u $VMUSER VBoxManage startvm "$VMNAME" --type headless
        echo ""
        ;;
    *)
        echo "Usage: sudo service vbox {start|stop|status|shutdown|reset|backup}"
        exit 1
        ;;
esac

exit 0

Tell the script be the first to shutdown and the last to startup:

sudo update-rc.d vbox defaults 99 01

To add backup task to crontab, run:

sudo crontab -e

And add a line like:

* 3 * * 5 service vbox backup

Which will run a weekly backup on Fridays at 3 AM. For more info on creating a crontab task see: http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

Related question: Bash script to wait for Virtualbox VM shutdown?