How to Create a VM on Ubuntu with Terraform, Libvirt, and QEMU: Solving Real-World Issues

Creating virtual machines (VMs) on Linux using Terraform and Libvirt is an excellent way to automate infrastructure, but the process can come with its fair share of challenges. In this article, I’ll walk you through how to set up a VM on Ubuntu using Terraform, Libvirt, and QEMU, and explain all the real-world issues I faced and solved along the way. Table of Contents Introduction Prerequisites Installing Required Packages Setting Up the Libvirt Pool Preparing the QCOW2 Image Writing the Terraform Configuration Common Errors and How to Fix Them Managing AppArmor Final Working Script Introduction Virtualization is a key component of modern infrastructure. With tools like Libvirt and QEMU, you can run lightweight VMs on a local or remote Linux host. Terraform adds the power of Infrastructure as Code to define and deploy VMs automatically. But things rarely work the first time. Prerequisites Ubuntu Linux (20.04 or later) A user with sudo privileges Terraform installed ( sudo apt install t...