Creating a KVM VM by hand is fine for learning. But for a lab of 5, 10 or 20 machines? Terraform automates the creation of libvirt VMs with reproducible configurations. This guide shows you how to do it properly, with Cloud-Init and the 2026 best practices.
What you will learn
- Write a reusable Terraform template to create KVM VMs
- Build a solid Cloud-Init configuration: SSH, hostname, packages
- Pin the community provider and understand what that implies
- Apply security best practices, without
security_driver = none - Troubleshoot a deployment without ever opening a graphical interface
Prerequisites
| Item | Version | Check |
|---|---|---|
| KVM/libvirt | Ubuntu 22.04+ or equivalent | virsh version |
| Terraform or OpenTofu | ≥ 1.6.0 | terraform version or tofu version |
| Cloud image | Ubuntu 24.04 QCOW2 | Download below |
| SSH key | Ed25519 recommended | ls ~/.ssh/id_ed25519.pub |
What you will build
The project is made of five HCL files (the Terraform configuration language) and two Cloud-Init files. This layout follows the official Terraform style guide: version constraints in terraform.tf, provider configuration in providers.tf, resources in main.tf, and the adjustable variables and the values returned after creation in their own files. Nothing forces you to split things this way, but it is what makes a project readable by someone else.
terraform-kvm/├── terraform.tf # Version constraints (Terraform, provider)├── providers.tf # libvirt provider configuration├── main.tf # Main resources├── variables.tf # Configurable variables├── outputs.tf # Outputs (IP, hostname)└── cloudinit/ ├── user-data.yaml # Cloud-Init configuration └── network-config.yamlTarget architecture:
┌─────────────────────────────────────────────────────────┐│ KVM host ││ ┌───────────────┐ ┌───────────────┐ ││ │ Default pool │ │ NAT network │ ││ │ (images) │ │ (192.168.122.x)│ ││ └───────┬───────┘ └───────┬───────┘ ││ │ │ ││ ▼ ▼ ││ ┌─────────────────────────────────────┐ ││ │ VM created by Terraform │ ││ │ • Ubuntu 24.04 (cloud image) │ ││ │ • Cloud-Init configured │ ││ │ • qemu-guest-agent installed │ ││ └─────────────────────────────────────┘ │└─────────────────────────────────────────────────────────┘Part 1: Prepare the environment
Terraform does not talk to KVM directly: it goes through libvirt, the management layer that exposes hypervisors behind a common API. Before writing a single line of configuration, the libvirtd daemon must be running, your account must reach it without sudo, and an operating system image must be available locally.
Check libvirt
These three checks prevent the most confusing errors, the ones where Terraform fails on a problem that has nothing to do with your code.
-
Check that libvirtd is running
Terminal window systemctl is-active libvirtdExpected output:
active -
Check that you belong to the libvirt group
Terminal window groups | grep -E "libvirt|kvm"If it is missing:
Terminal window sudo usermod -aG libvirt,kvm $USER# Then log out and log back in -
Test access to qemu:///system
Terminal window virsh -c qemu:///system list --allThis command must run without sudo. If it fails, see the Troubleshooting part.
Download the Ubuntu cloud image
A cloud image is not an installation ISO: it is an already installed QCOW2 disk, trimmed to the bare minimum, that waits for its Cloud-Init configuration at first boot. You download it once, and it then serves as the common base for every VM of the project, hence the separate base directory:
# Create a folder for the base imagessudo mkdir -p /var/lib/libvirt/images/base
# Download the Ubuntu 24.04 cloud imagesudo wget -O /var/lib/libvirt/images/base/ubuntu-24.04-server-cloudimg-amd64.img \ https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img
# Check the downloadqemu-img info /var/lib/libvirt/images/base/ubuntu-24.04-server-cloudimg-amd64.imgCreate the SSH key (if missing)
Cloud-Init will drop the public key into the VM; it is the only way to connect to it, since password authentication is disabled in the proposed configuration. The -N "" option creates the key without a passphrase, which is acceptable for a lab and should be avoided for a personal key.
# Generate an Ed25519 key (more secure than RSA)ssh-keygen -t ed25519 -C "terraform-kvm" -f ~/.ssh/id_ed25519 -N ""Part 2: The Terraform project
You now write the five files of the project. Terraform reads all the .tf files of a directory and merges them: their names have no technical meaning, they only organize the reading. The proposed order goes from the most constraining to the most variable: versions and connection, variables, resources, outputs.
Create the project structure
Two directories are enough: the project itself and a subfolder for the Cloud-Init templates. That subfolder matters: the files it holds are read by templatefile() and file() through path.module, the variable that designates the project directory, not the directory from which you run terraform:
mkdir -p ~/terraform-kvm/cloudinitcd ~/terraform-kvmterraform.tf and providers.tf files: versions and connection
A provider is the plugin that translates your resources into calls to an API,
here the libvirt one. Pinning its version is not a detail on this particular
provider: the 0.9.x branch rewrote the structure of almost every resource, and
a configuration written for 0.8 does not apply as it is. The ~> 0.9.0
constraint allows fixes but blocks the move to a later branch. The official
style guide puts these constraints in terraform.tf, a name to prefer over
versions.tf, which is very common but absent from the documentation. Create
terraform.tf:
terraform { required_version = ">= 1.6.0"
required_providers { libvirt = { source = "dmacvicar/libvirt" version = "~> 0.9.0" # 0.9.x only: the 0.9 branch rewrote the schema } }}The provider configuration lives apart, in providers.tf:
provider "libvirt" { # Connect to the system libvirt daemon (not the user session) uri = "qemu:///system"}One point deserves to be said before going further: dmacvicar/libvirt is a
community provider. Neither HashiCorp nor the libvirt project maintains it,
so it carries no support commitment and no guaranteed release cycle. That
does not disqualify it, it is the reference way to drive libvirt from
Terraform, but two consequences are better planned than endured: a libvirt
version may ship before the provider handles it, and an expected fix depends on
the availability of its maintainers. Hence the two habits that follow: pin the
version and commit .terraform.lock.hcl, so that the team and the CI use
exactly the same binary.
The single line of providers.tf deserves as much attention as the version constraint. The connection URI decides where your machines will be born, and the two possible values do not offer the same capabilities: system mode gives access to the shared pool and to every network mode, while session mode stays confined to the current user with a much more limited usermode network.
| URI | Access | Default pool | Network |
|---|---|---|---|
qemu:///system | All users | /var/lib/libvirt/images | Full (NAT, bridge) |
qemu:///session | Current user | ~/.local/share/libvirt/images | Limited (usermode) |
Choose qemu:///system for almost every case: it is the mode closest to production use, and the only one that lets you attach a VM to a bridge.
variables.tf file: configuration
Variables gather everything you will want to adjust without rereading the resource code: sizing, paths, network and storage pool names. Each one carries a default value, so the project works without providing any; passing a different value is then done with -var, a .tfvars file or a TF_VAR_ environment variable. Create variables.tf:
variable "vm_name" { description = "VM name" type = string default = "tf-kvm-01"}
variable "memory_mb" { description = "RAM in MB" type = number default = 2048}
variable "vcpu" { description = "Number of vCPUs" type = number default = 2}
variable "disk_size_gb" { description = "Disk size in GB (expansion of the cloud image)" type = number default = 20}
variable "base_image_path" { description = "Path to the base cloud image" type = string default = "/var/lib/libvirt/images/base/ubuntu-24.04-server-cloudimg-amd64.img"}
variable "ssh_public_key_path" { description = "Path to the public SSH key" type = string default = "~/.ssh/id_ed25519.pub"}
variable "network_name" { description = "Name of the libvirt network" type = string default = "default"}
variable "pool_name" { description = "Name of the libvirt storage pool" type = string default = "default"}main.tf file: resources
This is the core of the project, and it declares five resources that chain together. Two storage volumes first: the base image imported into the pool, then the VM disk created on top of it as a Copy-on-Write layer, which avoids duplicating several gigabytes per machine. Then the Cloud-Init configuration and the ISO image that carries it, and finally the domain, that is to say the VM itself. Terraform works out the creation order on its own from the references between resources. Create main.tf:
# ============================================================# libvirt provider 0.9.x - Complete configuration# ============================================================
# 1) Base volume (Ubuntu cloud image - local copy)resource "libvirt_volume" "base" { name = "ubuntu-24.04-base.qcow2" pool = var.pool_name
target = { format = { type = "qcow2" } }
create = { content = { url = var.base_image_path } }}
# 2) VM OS volume (CoW overlay on the base image)resource "libvirt_volume" "os_disk" { name = "${var.vm_name}.qcow2" pool = var.pool_name capacity = var.disk_size_gb * 1024 * 1024 * 1024 # Conversion to bytes
target = { format = { type = "qcow2" } }
# Use the base image as backing store (Copy-on-Write) backing_store = { path = libvirt_volume.base.path format = { type = "qcow2" } }}
# 3) Cloud-Init: generation of the configuration ISOresource "libvirt_cloudinit_disk" "init" { name = "${var.vm_name}-cloudinit"
user_data = templatefile("${path.module}/cloudinit/user-data.yaml", { hostname = var.vm_name public_key = file(pathexpand(var.ssh_public_key_path)) })
# meta_data is MANDATORY in 0.9.x meta_data = yamlencode({ instance-id = var.vm_name local-hostname = var.vm_name })
network_config = file("${path.module}/cloudinit/network-config.yaml")}
# 4) Volume for the Cloud-Init ISO (upload into the pool)resource "libvirt_volume" "cloudinit" { name = "${var.vm_name}-cloudinit.iso" pool = var.pool_name
create = { content = { url = libvirt_cloudinit_disk.init.path } }}
# 5) Domain (VM) - 0.9.x syntax with the devices blockresource "libvirt_domain" "vm" { name = var.vm_name type = "kvm" # Type is mandatory in 0.9.x memory = var.memory_mb memory_unit = "MiB" # MANDATORY: the provider's default unit is KiB vcpu = var.vcpu
# host-passthrough CPU: exposes every CPU flag of the host (AES-NI, # SSE4.x, AVX...). Without it, libvirt uses mode=custom model=qemu64, # which only exposes minimal x86_64 instructions, and recent kernels # (RHEL/AlmaLinux 10, Fedora >= 40) hang when loading the crypto # modules. cpu = { mode = "host-passthrough" }
os = { type = "hvm" type_machine = "q35" firmware = "efi" # Disable Secure Boot: libvirt 10+ enrolls the Microsoft keys by # default (OVMF_CODE_4M.ms.fd), which reject kernels not signed by # Microsoft. Linux cloud images boot, then hang at /init because # the virtio modules are not loaded. # Alphabetical order of the features is MANDATORY: the 0.9.x provider # returns the features sorted and compares them strictly with what # it was given (otherwise "Provider produced inconsistent result"). firmware_info = { features = [ { enabled = "no", name = "enrolled-keys" }, { enabled = "no", name = "secure-boot" }, ] } }
features = { acpi = true }
# devices block: mandatory structure in 0.9.x devices = { # OS disk disks = [ { # Explicit driver mandatory for qcow2! driver = { name = "qemu" type = "qcow2" } source = { volume = { pool = var.pool_name volume = libvirt_volume.os_disk.name } } target = { dev = "vda" bus = "virtio" } }, # Cloud-Init disk (CDROM) { device = "cdrom" driver = { name = "qemu" type = "raw" } source = { volume = { pool = var.pool_name volume = libvirt_volume.cloudinit.name } } target = { dev = "sda" bus = "sata" } } ]
# Network interface interfaces = [ { type = "network" model = { type = "virtio" } source = { network = { network = var.network_name } } } ]
# Serial console (essential for debugging) serials = [ { type = "pty" target = { port = 0 type = "isa-serial" } } ]
# QEMU agent channel: without it, qemu-guest-agent stays inactive in the VM channels = [ { source = { unix = {} } target = { virt_io = { name = "org.qemu.guest_agent.0" } } } ]
# Graphics support (optional, for virt-manager) graphics = [ { spice = { autoport = "yes" } } ] }
running = true}The channels block is the second classic omission of 0.9, and it does not
show at boot. Installing qemu-guest-agent in the VM is not enough: the agent
waits for a virtio-serial channel named org.qemu.guest_agent.0, which the
domain must declare. With provider 0.9.9, without this block, the service
stays inactive in the VM and virsh domifaddr --source agent answers
QEMU guest agent is not configured; with it, the service is active and the
command returns the interface address. The qemu_agent = true argument of the
0.8 versions no longer exists, this channel replaces it.
Cloud-Init configuration
Cloud-Init is the standard for configuring cloud machines at first boot: hostname, users, SSH keys, packages and final commands. The project uses two files, split by role: user-data.yaml describes the system and the accounts, network-config.yaml describes only the network interfaces. The first is a template filled in by Terraform, hence the ${hostname} and ${public_key} it contains.
Create cloudinit/user-data.yaml:
#cloud-config
# VM hostnamehostname: ${hostname}fqdn: ${hostname}.localmanage_etc_hosts: true
# Default userusers: - name: ubuntu groups: [adm, sudo] shell: /bin/bash sudo: ALL=(ALL) NOPASSWD:ALL lock_passwd: true # Disables the password (SSH key only) ssh_authorized_keys: - ${public_key}
# Packages to installpackages: - qemu-guest-agent # State and IP seen from the guest (needs the domain channel) - curl - vim - htop
# Enable the QEMU agent at bootruncmd: - systemctl enable --now qemu-guest-agent
# Allow SSH by key onlyssh_pwauth: false
# Update packages at first bootpackage_update: truepackage_upgrade: false # Avoids surprises in boot time
# Final messagefinal_message: | Cloud-init finished after $UPTIME seconds. Hostname: ${hostname} Connect with: ssh ubuntu@<IP>Create cloudinit/network-config.yaml:
version: 2ethernets: default: match: driver: virtio* # Match any virtio interface dhcp4: true dhcp6: falseThe match on the driver, and not on an interface name, is the point to remember in this file. Modern Ubuntu cloud images use predictable names derived from the hardware location (enp1s0, ens3), and eth0 no longer exists. Writing match: { driver: virtio* } therefore targets every virtio interface whatever name the VM gives it at boot, which makes the template reusable from one machine to the next.
outputs.tf file: retrieve information
In provider 0.9.x, the IP is no longer reachable directly through network_interface[0].addresses. You use a dedicated data source:
Create outputs.tf:
# Data source to get the IPs through DHCP leasesdata "libvirt_domain_interface_addresses" "vm" { domain = libvirt_domain.vm.name source = "lease" # Uses the libvirt DHCP server
depends_on = [libvirt_domain.vm]}
output "vm_name" { description = "VM name" value = libvirt_domain.vm.name}
output "vm_id" { description = "libvirt ID of the VM" value = libvirt_domain.vm.id}
output "vm_uuid" { description = "UUID of the VM" value = libvirt_domain.vm.uuid}
# All the IPs (0.9.x format: interfaces[].addrs[].addr)output "ip_addresses" { description = "IP addresses of the VM" value = [ for iface in data.libvirt_domain_interface_addresses.vm.interfaces : [for a in iface.addrs : a.addr] ]}
# Primary IP for convenienceoutput "primary_ip" { description = "Primary IP address of the VM" value = try( data.libvirt_domain_interface_addresses.vm.interfaces[0].addrs[0].addr, "Not available" )}
output "ssh_command" { description = "SSH command to connect" value = try( "ssh ubuntu@${data.libvirt_domain_interface_addresses.vm.interfaces[0].addrs[0].addr}", "IP not available - wait for cloud-init then: terraform apply -refresh-only" )}Part 3: Deploy the VM
The deployment follows the usual Terraform cycle: download the provider, validate the syntax, preview the changes, then apply. Only the last command changes anything on the machine; the three before it have no side effects and can be rerun freely.
Initialize and apply
Run these five steps from the project directory. Getting the IP address is handled separately because it depends on the VM booting, not on Terraform.
-
Initialize Terraform
Terminal window cd ~/terraform-kvmterraform initExpected output:
Initializing the backend...Initializing provider plugins...- Finding dmacvicar/libvirt versions matching "~> 0.9.0"...- Installing dmacvicar/libvirt v0.9.9...Terraform has been successfully initialized!The patch number depends on the day: the
~> 0.9.0constraint picks the most recent version of the 0.9 branch,0.9.9on September 30, 2026, and refuses any move to 0.10. The.terraform.lock.hclfile then freezes this choice for the whole team. -
Validate the configuration
Terminal window terraform validateExpected output:
Success! The configuration is valid. -
Preview the changes
Terminal window terraform planCheck that 5 resources will be created, that is to say all of the previous
main.tf:libvirt_volume.base, the downloaded cloud image, shared between VMslibvirt_volume.os_disk, the system disk derived from that baselibvirt_cloudinit_disk.init, the cloud-init configurationlibvirt_volume.cloudinit, the ISO volume that carries itlibvirt_domain.vm, the virtual machine that assembles everything
-
Apply
Terminal window terraform applyType
yesto confirm. -
Get the IP
Terminal window terraform output ip_addresses
Check the VM
These commands query libvirt directly, without going through Terraform: they show the real state of the hypervisor, independently of what Terraform believes it created. The --source agent option relies on qemu-guest-agent, installed by Cloud-Init in the VM, and gives the address seen from inside.
# VM statevirsh list --all
# Detailsvirsh dominfo tf-kvm-01
# IP through the QEMU agentvirsh domifaddr tf-kvm-01 --source agentConnect over SSH
The account created by Cloud-Init is named ubuntu and accepts your key only. The ssh_command output builds the complete line from the address it retrieved, which saves you from copying it by hand:
# Get the SSH commandterraform output ssh_command
# Or directly (replace the IP)ssh ubuntu@192.168.122.xxxPart 4: Debugging and troubleshooting
Failures fall into two families, which you must tell apart before looking for a cause: either the VM does not start at all, or it starts but stays unreachable. The first is diagnosed on the serial console, the second in the Cloud-Init logs. A VM listed as running by virsh proves nothing: it may very well be frozen while loading the kernel.
Serial console (no network)
If the VM does not start or does not get an IP, the serial console is the only channel available: it is attached to the domain's virtual serial port and shows the kernel messages from the very first moment of boot, before the network exists.
virsh console tf-kvm-01To exit: Ctrl + ]
Check Cloud-Init
Cloud-Init runs at first boot and applies the configuration carried by the ISO: hostname, account, SSH key, packages. If it fails, the VM boots but stays unusable, with no account and no key. These three commands, run from the console or over SSH, tell you where it stands and why it failed:
# Overall statuscloud-init status --long
# Detailed logssudo cat /var/log/cloud-init-output.log
# Applied configurationsudo cat /var/lib/cloud/instance/user-data.txt| Status | Meaning |
|---|---|
status: done | Cloud-Init finished successfully |
status: running | Still running (be patient) |
status: error | Error, check the logs |
Common problems
This table condenses the errors actually met with provider 0.9.x, several of which have no explicit message: the VM starts, uses CPU, and stays silent. Five rows concern traps specific to recent versions of libvirt and of the provider, hard to guess without having seen them: agent channel, Secure Boot, CPU model, order of the features and memory unit.
| Symptom | Likely cause | Solution |
|---|---|---|
Error: virsh: command not found | libvirt not installed | Installation guide (in French) |
failed to connect to the hypervisor | libvirtd stopped or permissions | sudo systemctl start libvirtd + check the group |
| Empty IP even after 1 minute | Data source read before the DHCP lease | terraform apply -refresh-only, then virsh net-dhcp-leases default |
QEMU guest agent is not configured | org.qemu.guest_agent.0 channel missing from the domain | Add the channels block in devices |
Permission denied on the pool | File rights or AppArmor | See the Security part below |
| Disk corrupted after apply | Source image modified | Use a read-only "golden" image |
Boot stuck in /init (AlmaLinux/RHEL 10) | Secure Boot enrolled by libvirt + MS keys | Add firmware_info.features with secure-boot=no + enrolled-keys=no |
| Kernel panic at boot (recent distros) | Generic qemu64 CPU without modern flags | Add cpu = { mode = "host-passthrough" } to the domain |
Provider produced inconsistent result on firmware_info.features | Provider 0.9.x bug: alphabetical sort on return | Declare the features in alphabetical order of name |
| VM at ~100% CPU, no network, no SSH (it "runs" but stays unreachable) | memory without memory_unit: the default is KiB, so memory = 2048 allocates 2 MiB of RAM | Add memory_unit = "MiB" to the libvirt_domain |
Boot drops into the BusyBox initramfs (mount /dev/vda1 ... failed: Invalid argument) | Truncated or corrupted source image: unreadable root FS | Check the image (qemu-img check, try a mount) and download it again from the official source |
The second trap produces exactly the same symptom, a silent hang in /init, for a totally different reason: the processor model. Without cpu = { mode = "host-passthrough" }, libvirt exposes to the VM a generic qemu64 CPU that has no AES-NI, no SSE4 and no AVX. The kernels of AlmaLinux 10, RHEL 10 and recent Fedora releases make cryptographic calls at boot that require these modern instructions, and the machine freezes when loading the first module.
The check is done after the apply: virsh dumpxml <vm> | grep cpu must show mode='host-passthrough'. A mode='custom' with <model>qemu64</model> points to the cause unambiguously. The host-passthrough mode has a downside: live migration becomes impossible to a host with a different processor, which is acceptable in a homelab or for training, and to weigh in multi-host production.
libvirtd logs
When the error occurs before the VM even starts (permission denied, volume not found, firmware missing), it is the daemon that logs it, not Terraform. The terraform apply message is often only a truncated summary of it:
# Real-time logsjournalctl -u libvirtd -f
# Recent errorsjournalctl -u libvirtd --since "10 minutes ago" | grep -i errorPart 5: Security: do not disable the protections
Permission errors on the storage pool are frequent, and the most shared solution on the web is to switch off the protection that causes them. It is a bad trade: the mechanism involved, sVirt, is precisely what prevents a compromised VM from reaching the disks of the others. Fixing the problem takes a few more minutes than disabling it.
Why do tutorials do it?
The shortcut can be explained, even if it cannot be justified. When Terraform, or you, creates a file in /var/lib/libvirt/images, that file may carry wrong security labels: libvirt then refuses to start the machine with a permission error, and the message does not say that the culprit is AppArmor or SELinux. Faced with an opaque error, switching off the whole mechanism is the solution that takes the least thought, and it is the one that circulates the most.
The real fix
It differs according to the security module of your distribution: AppArmor on Debian and Ubuntu, SELinux on RHEL, Rocky and AlmaLinux. In both cases, the point is to allow the pool path instead of disarming the mechanism.
-
Check the AppArmor profile
Terminal window sudo aa-status | grep libvirt -
Add the path to the profile if needed
If you use a custom pool (e.g.
/data/vms), edit:Terminal window sudo nano /etc/apparmor.d/local/usr.sbin.libvirtdAdd:
/data/vms/** rwk, -
Reload AppArmor
Terminal window sudo systemctl reload apparmorsudo systemctl restart libvirtd
-
Check the file context
Terminal window ls -Z /var/lib/libvirt/images/The files must have the
svirt_image_tcontext. -
Restore the context if it is wrong
Terminal window sudo restorecon -Rv /var/lib/libvirt/images/ -
For a custom path
Terminal window sudo semanage fcontext -a -t svirt_image_t "/data/vms(/.*)?"sudo restorecon -Rv /data/vms/
Default pool permissions
Before suspecting AppArmor or SELinux, check the classic UNIX permissions of the directory: a pool created by hand with the wrong owner produces exactly the same error.
# Check the ownerls -la /var/lib/libvirt/images/
# Must belong to root:root or libvirt-qemu depending on the distro# With 711 permissions on the folderMigration 0.8 → 0.9
If you have existing configurations with the 0.7 or 0.8 provider, here are the changes to apply. The 0.9.x branch is not an incremental evolution: flat attributes were replaced by nested objects, and repeatable blocks by lists. An existing configuration is therefore not fixed line by line, it is rewritten.
Summary table of changes
Each row gives the old form and its replacement. The last two are not provider changes but additions that became necessary with libvirt 10 and recent distributions.
| Element | Provider 0.8.x | Provider 0.9.x |
|---|---|---|
| libvirt_volume | source, format | create.content.url, target.format.type |
| backing file | base_volume_id | backing_store = { path, format } |
| libvirt_cloudinit_disk | optional meta_data | meta_data mandatory |
| libvirt_domain | disk {}, network_interface {} blocks | devices = { disks = [...], interfaces = [...] } |
| qcow2 driver | auto-detected | explicit, mandatory |
| IP retrieval | network_interface[0].addresses | data.libvirt_domain_interface_addresses |
| QEMU agent | qemu_agent = true | org.qemu.guest_agent.0 channel in devices.channels |
| CPU for recent distros | implicit | cpu = { mode = "host-passthrough" } often mandatory |
| UEFI Secure Boot | not auto-enrolled | auto-enrolled on libvirt 10+ → disable through firmware_info.features |
Migration example: libvirt_volume
The most visible change: one resource becomes two. In 0.8, a single libvirt_volume referenced the source image; in 0.9, the base image is imported into the pool by its own resource, which the VM disk then references as its backing store.
resource "libvirt_volume" "os_disk" { name = "vm.qcow2" pool = "default" source = "/var/lib/libvirt/images/base.img" format = "qcow2" size = 20 * 1024 * 1024 * 1024}# Base image (new, separate resource)resource "libvirt_volume" "base" { name = "base.qcow2" pool = "default"
target = { format = { type = "qcow2" } }
create = { content = { url = "/var/lib/libvirt/images/base.img" } }}
# VM disk with backing storeresource "libvirt_volume" "os_disk" { name = "vm.qcow2" pool = "default" capacity = 20 * 1024 * 1024 * 1024
target = { format = { type = "qcow2" } }
backing_store = { path = libvirt_volume.base.path format = { type = "qcow2" } }}Migration example: libvirt_domain
For the domain, all the repeatable blocks (disk, network_interface, console) disappear in favor of a devices object holding lists. Note also that qemu_agent and the cloudinit attribute are gone: the agent goes through a channel declared in devices.channels, and the Cloud-Init ISO becomes a disk like any other, declared as a CDROM in devices.disks.
resource "libvirt_domain" "vm" { name = "my-vm" memory = 2048 vcpu = 2
disk { volume_id = libvirt_volume.os_disk.id }
network_interface { network_name = "default" wait_for_lease = true }
cloudinit = libvirt_cloudinit_disk.init.id
console { type = "pty" target_port = "0" target_type = "serial" }
qemu_agent = true}resource "libvirt_domain" "vm" { name = "my-vm" type = "kvm" memory = 2048 memory_unit = "MiB" # otherwise read as KiB (default) = 2 MiB vcpu = 2
os = { type = "hvm" } features = { acpi = true }
devices = { disks = [ { driver = { name = "qemu", type = "qcow2" } source = { volume = { pool = "default" volume = libvirt_volume.os_disk.name } } target = { dev = "vda", bus = "virtio" } }, { device = "cdrom" driver = { name = "qemu", type = "raw" } source = { volume = { pool = "default" volume = libvirt_volume.cloudinit.name } } target = { dev = "sda", bus = "sata" } } ]
interfaces = [ { type = "network" model = { type = "virtio" } source = { network = { network = "default" } } } ]
serials = [ { type = "pty" target = { port = 0, type = "isa-serial" } } ]
# Replaces qemu_agent = true channels = [ { source = { unix = {} } target = { virt_io = { name = "org.qemu.guest_agent.0" } } } ]
graphics = [{ spice = { autoport = "yes" } }] }
running = true}Part 6: Create several VMs
Terraform offers two duplication mechanisms, and the choice between them comes down to one question: are the machines interchangeable? count produces an indexed list, suited to identical VMs; for_each produces a named collection, indispensable as soon as each machine has its own characteristics.
With count
count creates N copies of a resource, reachable by their position (count.index, starting at 0). The downside is that indexing: removing a VM from the middle shifts all the following ones, which Terraform will destroy and then recreate. To create 3 identical VMs, edit variables.tf:
variable "vm_count" { description = "Number of VMs to create" type = number default = 3}And adapt main.tf (0.9.x syntax):
# Base volume (shared by all the VMs)resource "libvirt_volume" "base" { name = "ubuntu-24.04-base.qcow2" pool = var.pool_name
target = { format = { type = "qcow2" } }
create = { content = { url = var.base_image_path } }}
# OS volumes for each VM (CoW overlay)resource "libvirt_volume" "os_disk" { count = var.vm_count name = "${var.vm_name}-${count.index + 1}.qcow2" pool = var.pool_name capacity = var.disk_size_gb * 1024 * 1024 * 1024
target = { format = { type = "qcow2" } }
backing_store = { path = libvirt_volume.base.path format = { type = "qcow2" } }}
# Cloud-init for each VMresource "libvirt_cloudinit_disk" "init" { count = var.vm_count name = "${var.vm_name}-${count.index + 1}-cloudinit"
user_data = templatefile("${path.module}/cloudinit/user-data.yaml", { hostname = "${var.vm_name}-${count.index + 1}" public_key = file(pathexpand(var.ssh_public_key_path)) })
meta_data = yamlencode({ instance-id = "${var.vm_name}-${count.index + 1}" local-hostname = "${var.vm_name}-${count.index + 1}" })
network_config = file("${path.module}/cloudinit/network-config.yaml")}
# Cloud-init volumesresource "libvirt_volume" "cloudinit" { count = var.vm_count name = "${var.vm_name}-${count.index + 1}-cloudinit.iso" pool = var.pool_name
create = { content = { url = libvirt_cloudinit_disk.init[count.index].path } }}
# Domains (VMs)resource "libvirt_domain" "vm" { count = var.vm_count name = "${var.vm_name}-${count.index + 1}" type = "kvm" memory = var.memory_mb memory_unit = "MiB" # provider default = KiB, always make it explicit vcpu = var.vcpu
os = { type = "hvm" } features = { acpi = true }
devices = { disks = [ { driver = { name = "qemu", type = "qcow2" } source = { volume = { pool = var.pool_name volume = libvirt_volume.os_disk[count.index].name } } target = { dev = "vda", bus = "virtio" } }, { device = "cdrom" driver = { name = "qemu", type = "raw" } source = { volume = { pool = var.pool_name volume = libvirt_volume.cloudinit[count.index].name } } target = { dev = "sda", bus = "sata" } } ] interfaces = [ { type = "network" model = { type = "virtio" } source = { network = { network = var.network_name } } } ] serials = [{ type = "pty", target = { port = 0, type = "isa-serial" } }] channels = [{ source = { unix = {} }, target = { virt_io = { name = "org.qemu.guest_agent.0" } } }] graphics = [{ spice = { autoport = "yes" } }] }
running = true}Adapt outputs.tf:
# Data source for each VMdata "libvirt_domain_interface_addresses" "vm" { count = var.vm_count domain = libvirt_domain.vm[count.index].name source = "lease"
depends_on = [libvirt_domain.vm]}
output "vms" { description = "Information about the VMs created" value = { for i, vm in libvirt_domain.vm : vm.name => { id = vm.id ip = try(data.libvirt_domain_interface_addresses.vm[i].interfaces[0].addrs[0].addr, "Not available") } }}With for_each (different VMs)
for_each walks through a map, here a dictionary where each key names a machine and each value carries its sizing. Because the identity of the resource rests on the key and not on a rank, removing an entry does not touch the others. This is the form to prefer for a cluster where the roles differ:
variable "vms" { description = "Map of the VMs to create" type = map(object({ memory = number vcpu = number disk = number })) default = { "master" = { memory = 4096, vcpu = 2, disk = 40 } "worker1" = { memory = 2048, vcpu = 2, disk = 20 } "worker2" = { memory = 2048, vcpu = 2, disk = 20 } }}The resources are then written as in the count example, replacing
count = var.vm_count with for_each = var.vms: the name of each object
uses each.key instead of count.index, the sizing is read from
each.value.memory, each.value.vcpu and each.value.disk, and the cross
references go from [count.index] to [each.key].
Part 7: Lifecycle and best practices
Three subjects only show up after a few weeks of use: the stacking of disk layers over successive applies, the fact that Cloud-Init does not replay its configuration on an existing VM, and the fragility of the state file.
Avoid uncontrolled QCOW2 chains
A QCOW2 disk laid down as copy-on-write only holds its differences from the base image: that is what makes creation instantaneous. The downside appears when successive terraform apply runs change the disk definition, because each layer is added to the previous one instead of replacing it. The chain gets longer, performance drops, and deleting an intermediate link makes all the following ones unreadable.
Rule: if you want a clean VM, run terraform destroy then terraform apply rather than successive applies.
Re-run Cloud-Init
Cloud-Init runs only once per instance. It recognizes an instance by its instance-id, which it stores in /var/lib/cloud/ at first boot. Editing user-data.yaml and rerunning an apply therefore changes nothing on a VM that has already started: the Cloud-Init ISO is indeed regenerated, but as long as the instance-id does not change, the machine does not replay its configuration. The block below shows two options, one local and one going through Terraform:
# Option 1: in the VM, clear the Cloud-Init cache and shut it downsudo cloud-init clean --logssudo poweroff# then, on the host, start it againvirsh start <vm-name>
# Option 2: recreate the VM (recommended with Terraform)terraform destroyterraform applyIn option 1, the full shutdown followed by a virsh start relaunches the QEMU process, which then reopens the Cloud-Init ISO as Terraform has just regenerated it. Changing the instance-id in meta_data leads to the same result by another route: as soon as the VM boots on an ISO that carries a new identifier, Cloud-Init sees a new instance and replays its whole configuration.
Back up the state
The terraform.tfstate file is Terraform's memory: it maps each declared resource to the real object created in libvirt. Losing it destroys no VM, but Terraform no longer recognizes them and will want to recreate them all, running into names that are already taken. It is the only file of the project that cannot be regenerated, and it may contain sensitive values: it does not go into Git with the .tf files.
# Back up locallycp terraform.tfstate terraform.tfstate.backup
# Or use a remote backend (S3, GitLab, etc.)Part 8: Variants
The configuration proposed so far covers the most common case, an isolated lab behind the libvirt NAT network. Three adaptations come up regularly: exposing the VMs on the physical network, adding a data disk separate from the system, and replacing Terraform with OpenTofu.
Use a bridge instead of NAT
With NAT, the VM is reachable from the host but invisible to the rest of the network; with a bridge, it gets an address from the LAN DHCP and becomes a machine like any other. On the Terraform side, the change comes down to three lines: the type goes from network to bridge, and the source block names the bridge instead of the libvirt network. If you have configured a bridge (see the networks guide (in French)), edit the interfaces section in the devices block:
# 0.9.x syntax for a bridgeinterfaces = [ { type = "bridge" model = { type = "virtio" } source = { bridge = { bridge = "br0" } } }]Add a data disk
Separating the system from the data makes resizing and backup easier: the data disk survives a recreation of the OS disk. It is declared as an ordinary volume, with no backing_store since it starts empty, then added to the devices.disks list with a free target.dev.
# Data volume (0.9.x syntax)resource "libvirt_volume" "data_disk" { name = "${var.vm_name}-data.qcow2" pool = var.pool_name capacity = 50 * 1024 * 1024 * 1024 # 50 GB
target = { format = { type = "qcow2" } }}
# In libvirt_domain, add the disk to devices.disks:devices = { disks = [ # ... existing OS disk ... { driver = { name = "qemu", type = "qcow2" } source = { volume = { pool = var.pool_name volume = libvirt_volume.data_disk.name } } target = { dev = "vdb" # Second disk bus = "virtio" } } ] # ... rest of the config ...}Use OpenTofu
OpenTofu is an open source fork of Terraform that reads the same .tf files, the same state and the same providers: no line of the previous configuration changes, only the name of the command differs. It is the way out if Terraform's license change is a problem in your context.
# Replace terraform with tofutofu inittofu plantofu applyCleanup
terraform destroy deletes the five resources in the reverse order of their creation, VM first, volumes after. The operation is irreversible and takes the machine's disk with its content: there is no per-resource confirmation and no trash. To delete all the resources created:
terraform destroyCheck that everything is gone:
virsh list --allvirsh vol-list defaultKey points
- Provider 0.9.x: completely different structure from 0.8.x, see the Migration section
- Explicit qcow2 driver: without
driver = { name = "qemu", type = "qcow2" }, the VM does not boot - Memory:
memory_unitmandatory: the provider's default unit is KiB, not MiB. Withoutmemory_unit = "MiB",memory = 2048allocates 2 MiB and the VM does not boot (kernel thrashing, no network). Always makememory_unit = "MiB"explicit. - meta_data mandatory:
libvirt_cloudinit_diskrequiresmeta_data = yamlencode({...}) - Cloud-Init network: use
match: { driver: virtio* }instead ofeth0 - IP retrieval:
libvirt_domain_interface_addressesdata source withsource = "lease" - Security: never disable
security_driver, fix the permissions - host-passthrough CPU: mandatory for AlmaLinux/RHEL 10 and recent Fedora, otherwise stuck in
/initat boot - QEMU agent: installing
qemu-guest-agentis not enough, the domain must declare theorg.qemu.guest_agent.0channel indevices.channels - UEFI Secure Boot: auto-enrolled on libvirt 10+ → disable through
firmware_info.featuresfor Linux cloud images not signed by Microsoft - Debug:
virsh console+cloud-init status --long+virsh net-dhcp-leases default - Cloud-Init does not replay its configuration on a VM that has already started: as long as the
instance-idstored in/var/lib/cloud/is the same, editinguser-data.yamlchanges nothing. Recreate the VM, change theinstance-id, or runcloud-init clean, shut the VM down withpoweroff, then start it again withvirsh start