Terraform is a popular tool for provisioning infrastructure on cloud providers such as EC2 and Azure, but there is also a provider written for local KVM libvirt resources.
Using the libvirt provider, we can use standard Terraform constructs to create local VMs, networks, and disks. And unlike older versions of this provider, the plugin binary is now automatically downloaded from the official terraform registry.
Prerequisite KVM and libvirt
As a prerequisite for this article, you must install KVM and libvirt as described here.
Install Terraform
Download the latest version of the binaries at the Terraform download page.
sudo apt install jq unzip git -y # get latest version using github api TERRA_VERSION=$(curl -sL https://api.github.com/repos/hashicorp/terraform/releases/latest | jq -r ".tag_name" | cut -c2-) # pull latest release wget -v4 https://releases.hashicorp.com/terraform/${TERRA_VERSION}/terraform_${TERRA_VERSION}_linux_amd64.zip # unzip unzip terraform_${TERRA_VERSION}_linux_amd64.zip # set permissions and move into path chmod +x terraform sudo mv terraform /usr/local/bin/. # validate terraform version
libvirt provider plugin
Older version of the libvirt terraform provider required that we manually deploy the plugin binary. This is no longer the case and we can simply reference the plugin and allow it to be pulled automatically from registry.terraform.io per the example below.
Simple VM using Terraform
As a simple test, you can use this “main.tf” terraform file to test a terraform init, then apply.
terraform { required_version = ">= 1.0.1" required_providers { libvirt = { source = "dmacvicar/libvirt" version = "0.6.10" } } } provider "libvirt" { uri = "qemu:///system" } resource "libvirt_domain" "terraform_test" { name = "terraform_test" }
You can download this main.tf from my github project also like below.
# get project git clone https://github.com/fabianlee/tf-libvirt-plugin-from-registry.git cd tf-libvirt-plugin-from-registry # download providers terraform init # create resources terraform apply
See my other article for more examples on using the libvirt provider and cloud-init.
REFERENCES
dmacvicar, terraform-provider-libvirt
NOTES
If you run into errors where “terraform init” does not download the libvirt provider and only works if using “sudo”, then remove the directory “~/.local/share/terraform/plugins/”