vmclone: Quickly spin up temporary VMs
I wanted a way to easily spin up graphical VMs for experimentation without affecting my main system. I ended up with a small command that clones a prepared VM, starts it, and opens its console:
vmclone my-clone
I'm using QEMU/KVM for virtualization. One can of course make clones in virt-manager by right clicking the VM and selecting "Clone", but this makes a full copy of the disk, wasting space. To avoid this, my script uses qemu-img directly to make a thin clone:
#!/bin/bash
if [[ $# != 1 || "$1" == "-h" || "$1" == "--help" ]]; then
echo "Usage: $0 vmclone CLONE_NAME" >&2
exit 1
fi
set -eux
conn=qemu:///system
base=base-desktop
clone="$1"
baseimg="$(virsh -c "$conn" domblklist "$base" | awk '$1=="vda" {print $2}')"
cloneimg="$(dirname "$baseimg")/$clone.qcow2"
qemu-img create -f qcow2 -b "$baseimg" -B qcow2 "$cloneimg"
virt-clone --connect "$conn" --original "$base" --name "$clone" --file "$cloneimg" --preserve-data
virsh -c "$conn" start "$clone"
virt-manager -c "$conn" --show-domain-console "$clone" &
Base image
The base image, base-desktop, is an Arch Linux VM that was installed with archinstall with the Xfce profile. After initial install, I added the appropriate guest agents and customized it to my liking:
pacman -Sy spice-vdagent qemu-guest-agent bash-completion firefox xorg-xrandr less
I also disabled the screensaver and screen blanking.
One gotcha is that screen resolution isn't automatically adjusted in the guest when resizing the console window. As a workaround, first enable resizing in the console with View → Scale Display → Auto resize VM with window. Then, after you resize the window, run xrandr -s 0 in the guest. For convenience, I added a launcher to the Xfce panel to do this.
Mark base image read-only
Once you make a clone, the base image must not change. To avoid accidental modification (which includes even just booting the VM), you should mark it read-only:
chmod a-w /var/lib/libvirt/images/base-desktop.qcow2
Modifying the base image
If you later want to make changes to the base image, you can use the following procedure:
cd /var/lib/libvirt/images
qemu-img create -f qcow2 -b base-desktop.N.qcow2 -B qcow2 base-desktop.NPLUS1.qcow2
virsh -c qemu:///system edit base-desktop
# [Change disk path to `base-desktop.NPLUS1.qcow2`]
# [Boot `base-desktop` VM and make any change you want, then power off]
chmod a-w base-desktop.NPLUS1.qcow2
With each change, increment the counter.
Compacting the base image chain
If you need to collapse the chain to save space, first detach any remaining clones:
qemu-img rebase -f qcow2 -b '' clone1.qcow2
...
Then you can safely collapse the chain:
chmod ug+w base-desktop.qcow2 base-desktop.*.qcow2
qemu-img commit -f qcow2 -b base-desktop.qcow2 base-desktop.HIGHEST.qcow2
virsh -c qemu:///system edit base-desktop
# [Change disk path to `base-desktop.qcow2`]
rm base-desktop.*.qcow2
chmod a-w base-desktop.qcow2