Scripted creation of VMs in VirtualBox

September 2010


Whereas VMWare has a rather unwieldy installer that needs to be run when an Ubuntu PC is installed, VirtualBox is neatly packaged for Ubuntu. It is possible to control VirtualBox from the command line, and we do so to install Windows machine using an ISO image of a CD that does a complete installation, including some applications like virus scanners and the like:

  1. Set a few variables

    user@host:~$ VMPATH=/mnt/scratch/virtualbox
    user@host:~$ VMNAME=VirtualBox-Windows
    user@host:~$ VMFILE=${VMPATH}/${VMNAME}/${VMNAME}.xml
    user@host:~$ VDISK=${VMPATH}/${VMNAME}/${VMNAME}-disk
    user@host:~$ INSTALLISO=/opt/iso/windows/unattend.ISO
    user@host:~$ install -d ${VMPATH}

  2. Create the VM and register it to VirtualBox

    user@host:~$ VBoxManage createvm \
    --name ${VMNAME} \
    --ostype WindowsXP \
    --basefolder ${VMPATH} \
    --register

  3. Adjust the VM a bit

    Give the VM 512 MB of memory, and one CPU:

    user@host:~$ VBoxManage modifyvm ${VMNAME} \
    --memory 512 \
    --cpus 1

  4. Add an IDE controller to the VM

    user@host:~$ VBoxManage storagectl ${VMNAME} \
    --name "IDE Controller" \
    --add ide

  5. Create a virtual disk, and register it

    user@host:~$ VBoxManage createhd --filename ${VDISK} \
    --size 30000 \
    --variant Split2G \
    --remember

    [Warning]Warning

    The Split2G doesn't seem to have any effect.

  6. Register the virtual DVD with VirtualBox

    user@host:~$ VBoxManage openmedium \
    dvd ${INSTALLISO}

  7. Fetch the machine's UUI from its description XML file

    user@host:~$ eval $(grep '<Machine uuid=[{0-9a-f}]*' ${VMFILE}|tr -d '{}'|grep -o 'uuid=[^\ ]*')
    user@host:~$ UUID=${uuid}

  8. Attach the virtual disk to the virtual machine

    user@host:~$ VBoxManage showvminfo ${VMNAME}|fgrep '${VDISK}.vdi' \
    || VBoxManage storageattach ${VMNAME} \
    --storagectl "IDE Controller" \
    --port 0 \
    --device 0 \
    --type hdd \
    --medium ${VDISK}.vdi

  9. Attach the installation DVD to the virtual machine

    user@host:~$ VBoxManage showvminfo ${VMNAME}|fgrep '${INSTALLISO}' \
    || VBoxManage storageattach ${VMNAME} \
    --storagectl "IDE Controller" \
    --port 1 \
    --device 0 \
    --type dvddrive \
    --medium ${INSTALLISO}

  10. Start the VM

    user@host:~$ VBoxManage startvm ${UUID} \
    --type gui