Linked clones

One of the nice features of VirtualBox is it allows you to created linked clones. Unlike a full clone of a virtual machine, a linked clone shares an existing disk image. This significantly reduces the space required when running multiple virtual machines. For the example in this post the base installation used 1022M of disk space, however the linked clone used just 37M of additional space.


Before creating a linked clone, a base image needs to be created. There are many ways you could go about doing this. For this post I'm going to kickstart a CentOS virtual machine as described in a previous post. However you build the system, end result should look something like this:

 showing a single VM before a clone is created.

Clone script

Although it's possible to manually create a linked clone, in the long run it's quicker to automate the process. VirtualBox provides a command line tool called VBoxManager. The bash script below uses VBoxManager to create a linked clone:

# Create and start a linked clone in VirtualBox. This script assumes a base
# image has already been created.
#   Usage: ./ [CLONE_NAME]
set -e

BASE_VM='CentOS 7.2'
VM_PATH="${HOME}/VirtualBox VMs/${BASE_VM}"
VBoxManage='/c/Program Files/Oracle/VirtualBox/VBoxManage'
[ "$#" -eq 1 ] && CLONE_NAME="$1"

if ! "$VBoxManage" list vms | grep -q "^.${BASE_VM}. "; then
  echo "Missing VM: ${BASE_VM}" >&2
  exit 1

"$VBoxManage" snapshot "$BASE_VM" list --machinereadable || \
  "$VBoxManage" snapshot "$BASE_VM" take 'clone_base' --description 'Base snapshot for linked clones'

"$VBoxManage" clonevm "$BASE_VM" --snapshot 'clone_base' --options link --name "$CLONE_NAME" --register
"$VBoxManage" startvm "$CLONE_NAME"

exit 0

Note: this script is designed to run on Windows under a Cygwin environment. It should be trivial to adapt it to work under a different operating system. You may also need to tweak the variables set at the top of the script before running it.

Running the clone script

Running the script will run through the following steps:

  1. Check the base virtual machine exists.
  2. Create a snapshot of the base image if no snapshot exists.
  3. Create a linked clone using the snapshot.
  4. Power on the linked clone.

The steps above should take a few seconds. Assuming everything was successful you should see a new virtual machine:

 showing the created linked clone.