How to clone existing KVM virtual machine images on Linux
I
wanted to clone my Debian or Ubuntu Linux KVM VM for testing purpose. How do I clone existing virtual machine images under KVM?
You can use a simple command named virt-clone. It is a command line utility for cloning existing virtual machine images using the “libvirt” hypervisor management library. It will copy the disk images of any existing virtual machine, and define a new guest with an identical virtual hardware configuration. Elements which require uniqueness will be updated to avoid a clash between old and new guests.
How to clone your VM and spawn new instances in KVM
The syntax is
# virt-clone –original {Domain-Vm-Name-Here} –auto-clone
OR
# virt-clone –original {Domain-Vm-Name-Here} \
–name {New-Domain-Vm-Name-Here}
Examples
First VM/domain with devices to clone must be paused or shutoff. To gracefully shutdown a domain named ubuntu-box1, run:
$ sudo virsh shutdown ubuntu-box1
OR you can paused it as follows:
$ sudo virsh suspend ubuntu-box1
$ virsh list
Sample outputs:
Domain ubuntu-box1 suspended
Id Name State
1 freebsd running
5 ubuntu-box1 paused
Let us generate a new guest name, and paths for new storage automatically for a vm called ubuntu-box1
$ sudo virt-clone –original ubuntu-box1 –auto-clone
Sample outputs:
WARNING Setting the graphics device port to autoport, in order to avoid conflicting.
Allocating ubuntu-box-1-clone.qcow2 | 40 GB 00:00:04
Clone ubuntu-box1-clone created successfully.
The above command cloned the guest called “demo” on the default connection, auto generating a new name called ubuntu-box1-clone and disk clone path. You can start or resume original domain:
$ sudo virsh start ubuntu-box1
OR
$ sudo virsh resume ubuntu-box1
Next, start ubuntu-box1-clone, enter:
$ sudo virsh start ubuntu-box1-clone
Verify it:
$ virsh list
My dhcpd server gave 192.168.2.147 IP address to ubuntu-box1-clone VM, run:
$ ping -c2 192.168.2.147
Finally, ssh into the box:
$ ssh vivek@192.168.2.147
Sample sessions:
Fig.01 virt-clone command cloned existing virtual machine images
Please note, virt-clone does not change anything inside the guest OS, it only duplicates disks and does host side changes. So things like changing passwords, changing static IP address, ssh-keys, hostnames etc are outside the scope of this tool. Once login using to cloned VM using ssh, you can change those:
$ ssh vivek@192.168.2.147
$ sudo -s
# echo ubuntu-box1-clone > /etc/hostname
# sed -i s/ubuntu-box1/ubuntu-box1-clone/g /etc/hosts
# reboot
# /bin/rm -v /etc/ssh/ssh_host_*
# dpkg-reconfigure openssh-server
# passwd vivek
You can use virt-sysprep instead of virt-clone if you need to clone the VM and make/reset anything inside the guest OS.