This guide will help you set up a virtual machine using QEMU/KVM with libvirt through Terraform.
- Ubuntu 24.10 with QEMU, KVM, and libvirt installed
- Terraform v1.10.5 installed
terraform-provider-libvirt(dmacvicar/libvirt) plugin installed
For a quick automated setup, you can use the provided script:
# Make the script executable
chmod +x script/setup-libvirt.sh
# Run the automated setup
./script/setup-libvirt.shThis script will:
- Install QEMU/KVM and libvirt packages
- Create and configure the default storage pool
- Set proper permissions
- Add your user to the libvirt group
- Download and prepare the Ubuntu Cloud image
- Provide the absolute path to use in your Terraform configuration
After running the script, log out and log back in for group membership changes to take effect.
If you prefer to set up everything manually, follow these steps:
To avoid permission denied errors when using Terraform with libvirt, modify the /etc/libvirt/qemu.conf file:
sudo nano /etc/libvirt/qemu.confFind the following line:
# security_driver = "selinux"Change it to:
security_driver = "none"Then restart libvirt:
sudo systemctl restart libvirtdIf you have a predefined Terraform configuration, clone the repository:
git clone https://github.com/ArmanTaheriGhaleTaki/terraform-libvirt-sample.git
cd terraform-libvirt-sampleRun the following command to initialize the Terraform working directory:
terraform initBefore applying the configuration, validate and check the execution plan:
terraform validate
terraform planOnce validated, apply the configuration to create the virtual machine:
terraform apply -auto-approveTo customize your VM’s initialization process, update the Cloud-Init configuration according to your needs. Modify user-data and meta-data files accordingly.
If you configure a static IP for the VM, Terraform will not terminate successfully and will keep retrying endlessly. However, this is expected behavior, and you can safely interrupt the process and SSH into the server manually without issues.
If you need to remove the VM, use:
terraform destroy -auto-approveThe repository includes an automated setup script (script/setup-libvirt.sh) that handles the initial configuration of your system for libvirt and QEMU/KVM. This script:
- Installs Dependencies: Automatically installs
qemu-kvm,libvirt-daemon-system, andvirt-manager - Configures Storage Pool: Creates and configures the default storage pool at
/var/lib/libvirt/images/default - Sets Permissions: Ensures proper ownership and permissions for the storage pool
- Downloads Cloud Image: Downloads the Ubuntu Jammy (22.04) cloud image and resizes it by +50G
- User Configuration: Adds your user to the libvirt group for proper access
The script provides the absolute path of the downloaded image, which you can use directly in your variables.tf file.
Special thanks to Molla Salehi (GitHub: mm3906078) for contributions and guidance.