A Faster Way to Create Virtual Machines with Cloud Images and virt-manager

I’ve written previously about Booting Cloud Images with QEMU. However, I’ve since graduated to a more convenient method of spawning virtual machines. This method is also much faster and is more cohesive with the rest of the virtualization stack that you’ll find on your Linux distribution. As someone who creates and tears down tons of virtual machines for testing things, this method appeals to me more than the previous. Let’s get into it.

Download a Cloud Image

Ideally, you’ll find a download link for a QCOW2 VM image. Otherwise, you’ll need to convert it with qemu-img convert. As before, I will use a Fedora cloud image.

# mkdir /var/lib/libvirt/images/base
# cd /var/lib/libvirt/images/base
# curl -LkO https://download.fedoraproject.org/pub/fedora/linux/releases/34/Cloud/x86_64/images/Fedora-Cloud-Base-34-1.2.x86_64.qcow2

Generate a cloud-init bootstrap image

This can be a one-time thing, if you don’t mind each of your new VMs taking on these settings.

# mkdir cloud-init-bootstrap
# cd cloud-init-bootstrap
# touch meta-data
# cat > user-data <<EOF

    name: fedora

  list: |
  expire: False

resize_rootfs: True
# genisoimage -output seedci.iso -volid cidata -joliet -rock user-data meta-data

Obviously, if this machine is going to be accessible via the Internet, you’ll want to follow some better security practices. For testing kernel changes, it’s probably fine.

Create a disk for the new VM

You can just use exactly what was downloaded, however, I like to create a new image which is based on the original download. That way I can create new VM disks without having to re-download or remember to copy and paste the original disks. It’s also convenient to make a larger disk than the base image, as cloud-init will take care of resizing the file system for you.

# qemu-img create -f qcow2 \
  -b /var/lib/libvirt/images/base/Fedora-Cloud-Base-34-1.2.x86_64.qcow2 \
  -F qcow2 \
  /var/lib/libvirt/images/fedora-34.qcow2 15G

I tend to name the disk what I intend to name the virtual machine for identification purposes.

Create the new domain (VM)

virt-manager comes with a helpful tool called virt-install to provision a new virtual machine. Note that the shell prompt has switched from root to a user session.

$ virt-install --name fedora-34 --os-variant fedora --vcpus 2 --memory 2048 \
  --graphics vnc --virt-type kvm --disk /var/lib/libvirt/images/fedora-34.qcow2 \
  --cdrom /var/lib/libvirt/images/base/cloud-init-bootstrap/seedci.iso

Enjoy your new virtual machine

The VM may now be managed on the command line with virsh or with the virt-manager GUI. You could leave this one in its current state and simply clone new VMs from it whenever you’d like a brand-new one, or follow these same steps again for new VMs.