Libiticum.nl

Commandline, linux, provisioning, virtualization

KVM with Terraform ubuntu 20.04 LTS

sander

Install KVM and Bridge networking from one of the various sources from the net. The one i used was: https://www.linuxtechi.com/install-kvm-on-ubuntu-20-04-lts-server/

Install terraform by using one of the many sources on the net: the one i used was: https://computingforgeeks.com/how-to-provision-vms-on-kvm-with-terraform/

Here are the things not to forget:

* On Ubuntu distros SELinux is enforced by qemu even if it is disabled globally, this might cause unexpected `Could not open ‘/var/lib/libvirt/images/<FILE_NAME>’: Permission denied` errors. Double check that `security_driver = “none”` is uncommented in `/etc/libvirt/qemu.conf` and issue `sudo systemctl restart libvirt-bin` to restart the daemon.

Furthermore i used the following tf file for deploying a VM with my bridge as interface

terraform {
  required_providers {
    libvirt = {
      source = "dmacvicar/libvirt"
    }
  }
}

# Above here is not mentioned in examples on net but needed to work.

provider "libvirt" {
  uri = "qemu:///system"
}

#provider "libvirt" {
#  alias = "server2"
#  uri   = "qemu+ssh://root@192.168.100.10/system"
#}

resource "libvirt_volume" "centos7-qcow2" {
  name = "db.qcow2"
  pool = "default"
  #source = "https://cloud.centos.org/centos/7/images/CentOS-7-x86_64-GenericCloud.qcow2"
  source = "./CentOS-7-x86_64-GenericCloud.qcow2"
  format = "qcow2"
}

data "template_file" "user_data" {
  template = "${file("${path.module}/cloud_init.cfg")}"
}

# Use CloudInit to add the instance
resource "libvirt_cloudinit_disk" "commoninit" {
  name = "commoninit.iso"
  user_data      = "${data.template_file.user_data.rendered}"
}

# Define KVM domain to create
resource "libvirt_domain" "db1" {
  name   = "db1"
  memory = "1024"
  vcpu   = 1

  #network_interface {
  #  network_name = "default"
  network_interface {
    bridge = "br0"
  }

  disk {
    volume_id = "${libvirt_volume.centos7-qcow2.id}"
  }

  cloudinit = "${libvirt_cloudinit_disk.commoninit.id}"

  console {
    type = "pty"
    target_type = "serial"
    target_port = "0"
  }

  graphics {
    type = "spice"
    listen_type = "address"
    autoport = true
  }
}

# Output Server IP
output "mac" {
#  value = "${libvirt_domain.db1.network_interface.0.addresses.0}"
  value = "${libvirt_domain.db1.network_interface.0.mac}"

And i use the following cloud_init.cfg

ssh_pwauth: True
chpasswd:
  list: |
     root: StrongPassword
  expire: False

users:
  - name: <your preferred username>
    ssh_authorized_keys:
      - ssh-rsa ........
    sudo: ['ALL=(ALL) NOPASSWD:ALL']
    shell: /bin/bash
    groups: wheel

Download the centos iso locally:

wget https://cloud.centos.org/centos/7/images/CentOS-7-x86_64-GenericCloud.qcow2

Make sure the tf file, cloud_init.cfg and the qcow2 file are in the same directory

terraform plan -out plan.out

terraform apply plan.out

Back to top