kvm-qemu: scripted clones of virtual machines

KVM is quickly becoming a viable competitor to paid vendors given the wide variety of features it offers in comparison (Memory page sharing, live migration, HA clustering, the list goes on and on…). Cloning virtual machines is common practice when deploying large environments with many virtual machines. Here’s a quick and dirty way to clone a virtual machine that could easily be scripted to deploy a large number of virtual machines:

Let’s assume you have a base disk for CentOS 6 you want to clone with the following details:

Source volume (disk) = /data/VMs/centOS6.img
Source volume pool = VMs
Destination disk = /data/VMs/centOS6-clone.img
Amount of RAM = 2GB

Step 1: Clone the source volume. This can easily be done with virsh:

[root@localhost ~]# virsh vol-clone centOS6.img centOS6-clone.img --pool VMs

Step 2: Create your VM from the newly cloned volume using virt-install:

[root@localhost ~]# virt-install --name centOS6-clone --ram 2000 --noautoconsole --noreboot --import --disk /data/VMs/centOS6-clone.img

This assumes a few things:

  1. You have a file based storage pool located at /data/VMs/
  2. You do not want the VM to power on after the installation is complete (–noreboot)

Aside from that, you could quickly quickly create a source and destination VM matrix and read the information into a script via arguments. Gratuitous example:


usage="$0 <file> where <file> contains VM information \
in the following format:\n <source disk>,<new disk>,\
amount of RAM (in megabytes),<volume pool>"

cloneSystem ()
for i in `cat $1`
        # Field 1 - Your source disk
        sdisk=`echo $i|cut -f 1 -d ,`
        # Field 2 - Your new disk
        ndisk=`echo $i|cut -f 2 -d ,`
        # Field 3 - Amount of RAM for your VM
        ram=`echo $i|cut -f 3 -d ,`
        # Field 4 - Your volume pool
        vpool=`echo $i|cut -f 4 -d ,`
        # Derives new VM name based on destination disk name without the file extension
        nvm=`echo $i|cut -f 2 -d ,|cut -f 1 -d .`

        # Clone the source disk - asynchronous
        `virsh vol-clone $sdisk $ndisk --pool $vpool`
        # Create the new VM - do not power it on
        `virt-install --name $nvm --ram $ram --noautoconsole --noreboot --import --disk $sdisk`


if [ $# -ne 1 ] # no arguments
        echo -e $usage
elif [ ! -f $1 ] # file doesn't exist
        echo -e $usage
elif [ -f $1 ] # file exists begin clone - assumes file is in the proper format
        cloneSystem $1

Leave a Reply

Your email address will not be published. Required fields are marked *