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.
Setup
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:
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:
#!/bin/bash
#
# Create and start a linked clone in VirtualBox. This script assumes a base
# image has already been created.
#
# Usage: ./clone.sh [CLONE_NAME]
#
set -e
BASE_VM='CentOS 7.2'
VM_PATH="${HOME}/VirtualBox VMs/${BASE_VM}"
VBoxManage='/c/Program Files/Oracle/VirtualBox/VBoxManage'
CLONE_NAME='clone'
[ "$#" -eq 1 ] && CLONE_NAME="$1"
if ! "$VBoxManage" list vms | grep -q "^.${BASE_VM}. "; then
echo "Missing VM: ${BASE_VM}" >&2
exit 1
fi
"$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:
- Check the base virtual machine exists.
- Create a snapshot of the base image if no snapshot exists.
- Create a linked clone using the snapshot.
- Power on the linked clone.
The steps above should take a few seconds. Assuming everything was successful you should see a new virtual machine: