How to create a KVM template on Arch Linux
Posted on Fri 30 October 2020 in arch
If you are deploying many virtual machines, templates can be leveraged to save time and even storage if using thin provisioning.
The process of creating a template is two steps:
- Create and configure the base operating system image
- Use sysprep to remove system-specific settings
Once completed we can create virtual machines based on the templates.
Install libraries and enable KVM services
pacman -S virt-manager qemu vde2 iptables ebtables dnsmasq bridge-utils openbsd-netcat libguestfs cpio
# enable services
systemctl enable libvirtd.service
systemctl start libvirtd.service
Allow user account to use KVM
Edit /etc/libvirt/libvirtd.conf
# uncomment the following
...
unix_sock_group = "libvirt"
...
# be careful to uncomment the 'rw' permissions not the 'ro'
unix_sock_rw_perms = "0770"
Add current user to libvirt group
usermod -a -G libvirt $(whoami)
newgrp libvirt
# the newgrp command is a gem, no need to logout for the group to take effect
Restart the libvirt daemon:
systemctl restart libvirtd.service
Create image for base Ubuntu install
qemu-img create -o preallocation=metadata -f qcow2 images/Template-ubuntu20.04.qcow2 10G
Start the default network
virsh net-start default
virsh net-autostart default
Install the guest operating system
virt-install --virt-type kvm --name Template-ubuntu20.04 --ram 8196 --disk /usr/libvirt/images/ubuntu.qcow2,format=qcow2
--vcpus 4
--network network=default
--graphics vnc,listen=0.0.0.0 --noautoconsole
--os-type=linux --os-variant=ubuntu20.04
--cdrom=/usr/libvirt/images/ubuntu-20.04.1-desktop-amd64.iso
From the host, SSH into the guest to verify it is working
You can use the following command to find the ip address of the guest machine:
virsh net-dhcp-leases default | awk '{print $5, $6}'
Use the ip address above to test SSH is working
Configure the guest operating system
Continue to configure the system. At the very least update the system:
sudo apt-get update
sudo apt-get upgrade
Sysprep the image to prepare for template
virt-sysprep -v -d Template-ubuntu20.04
virsh undefine Template-ubuntu20.04
Dump the configuration to XML
virsh dumpxml ubuntu20.04-base > /usr/libvirt/virtual_machines/images/base-image.xml
Create a clone using the template
# first create a new image using the base template
qemu-img create -b Template-ubuntu20.04.qcow2 -F qcow2 -f qcow2 ubuntu-clone.qcow2
# resize the image to be an appropriate size
qemu-img resize /usr/libvirt/virtual_machines/images/ubuntu-clone.qcow2 +50G
# clone the virtual machine,
virt-clone --original-xml=/usr/libvirt/virtual_machines/images/base-image.xml -f /usr/libvirt/virtual_machines/images/ubuntuXX.qcow2 -n ubuntuXX --preserve-data
Your virtual machine is now cloned using the thin provisioning method.