How to use Terraform with Libvirt / KVM
Installing Terraform
First we need to install Terraform so we can start building infrastructure. I will be installing Terraform on Ubuntu 18.04.5 LTS. Commands for your operating system may be a little different.
Installation instructions for other operating systems can be found within Terraform’s installation documentation
> Add GPG key
$ curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
> Add HashiCorp repo
$ sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
> Update and Install
$ sudo apt-get update && sudo apt-get install terraform
Setting up Libvirt / KVM as a Terraform provider
In Terraform v0.13 and above, the devs changed how in-house Providers work. Libvirt/KVM is considered an in-house provider, so we need to do a few extra steps to get our environment ready. Below are steps on how to build from source and install dmacvicar/terraform-provider-libvirt
to be able to use libvirt/KVM locally with Terraform.
Requirements:
Installation Steps:
- Create required directories for new in-house provider structure (change version number if you are using a different version)
$ mkdir -p ~/.local/share/terraform/plugins/registry.terraform.io/dmacvicar/libvirt/0.6.3/linux_amd64/repoDownload
- Clone dmacvicar/terraform-provider-libvirt repo and make
$ cd ~/.local/share/terraform/plugins/registry.terraform.io/dmacvicar/libvirt/0.6.3/linux_amd64/repoDownload
$ git clone https://github.com/dmacvicar/terraform-provider-libvirt.git
$ cd terraform-provider-libvirt
$ make
$ cd ~/.local/share/terraform/plugins/registry.terraform.io/dmacvicar/libvirt/0.6.3/linux_amd64
$ mv ~/.local/share/terraform/plugins/registry.terraform.io/dmacvicar/libvirt/0.6.3/linux_amd64/repoDownload/terraform-provider-libvirt/terraform-provider-libvirt .
Testing Terraform with new Libvirt provider
Now that Terraform and Libvirt provider are setup and ready to be used…let’s test it! Below is a simple main.tf
file used to create and deploy a simple test VM.
Testing Steps:
- Create and
cd
into directory where your Terraform configuration files will be stored - Initiate working directory
$ terraform init
- Terraform plan and apply
> Terraform Plan
$ terraform plan
> Terraform Apply
$ terraform apply
You should now see your newly created VM! Below is what it looks like for me.
- Terraform destroy to remove newly created test VM
$ terraform destroy
main.tf file:
terraform {
required_providers {
libvirt = {
source = "dmacvicar/libvirt"
version = "0.6.3"
}
}
}
provider "libvirt" {
uri = "qemu:///system"
}
resource "libvirt_domain" "terraform_test" {
name = "terraform_test"
}