Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 13: VMs als Code mit OpenTofu

Ziel: VMs, Platten und cloud-init mit OpenTofu und dem libvirt-Provider beschreiben, anlegen, ändern und wieder abbauen. Und die Grenzen des Providers kennen. · Dauer: ca. 75 min · Voraussetzung: Tag 12

Briefing

  • OpenTofu ist der freie Ableger von Terraform. Du beschreibst den Sollzustand in .tf-Dateien. tofu plan zeigt den Unterschied zum Istzustand, tofu apply stellt ihn her.
  • Der Provider dmacvicar/libvirt übersetzt Ressourcen in libvirt-Objekte: libvirt_volume wird zum Volume, libvirt_domain zur Domain, libvirt_cloudinit_disk zum Seed-ISO.
  • Seit Version 0.9 bildet der Provider die Domain-XML fast eins zu eins ab: devices.disks, devices.interfaces und so weiter. Wer die XML aus Tag 3 kennt, findet sich zurecht.
  • OpenTofu merkt sich, was es angelegt hat, im State (terraform.tfstate). Was nicht im State steht, fasst es nicht an.
 main.tf ── tofu apply ──► libvirt auf kvm1
   for_each namen = ["tofu1", "tofu2"]
     libvirt_volume.platte     tofu1.qcow2 (Overlay auf basis/noble.qcow2)
     libvirt_cloudinit_disk    Seed-ISO bauen
     libvirt_volume.seed       tofu1-seed.iso im Pool default
     libvirt_domain.vm         Domain tofu1

Drill 1: OpenTofu installieren

Auf kvm1, als Paket aus den Releases von OpenTofu:

cd /tmp
wget -q \
  https://github.com/opentofu/opentofu/releases/download/v1.13.9/tofu_1.13.9_amd64.deb
sudo apt-get install -y ./tofu_1.13.9_amd64.deb
tofu version

Erwartet (gekürzt):

OpenTofu v1.13.9
on linux_amd64

Fortschritt speichern? Kostenlos registrieren

Drill 2: Die Konfiguration

mkdir -p ~/kvm-lab/tag13
cd ~/kvm-lab/tag13
cat > main.tf <<'EOF'
terraform {
  required_providers {
    libvirt = {
      source  = "dmacvicar/libvirt"
      version = "0.9.9"
    }
  }
}

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

variable "namen" {
  type    = set(string)
  default = ["tofu1", "tofu2"]
}

resource "libvirt_volume" "platte" {
  for_each = var.namen
  name     = "${each.key}.qcow2"
  pool     = "default"
  capacity = 10737418240
  target = {
    format = { type = "qcow2" }
  }
  backing_store = {
    path   = "/var/lib/libvirt/images/basis/noble.qcow2"
    format = { type = "qcow2" }
  }
}

resource "libvirt_cloudinit_disk" "seed" {
  for_each  = var.namen
  name      = "${each.key}-seed"
  user_data = <<-EOT
    #cloud-config
    users:
      - name: ubuntu
        sudo: ALL=(ALL) NOPASSWD:ALL
        shell: /bin/bash
        ssh_authorized_keys:
          - ${trimspace(file(pathexpand("~/.ssh/id_ed25519.pub")))}
  EOT
  meta_data = <<-EOT
    instance-id: ${each.key}-001
    local-hostname: ${each.key}
  EOT
}

resource "libvirt_volume" "seed" {
  for_each = var.namen
  name     = "${each.key}-seed.iso"
  pool     = "default"
  create = {
    content = { url = libvirt_cloudinit_disk.seed[each.key].path }
  }
}

resource "libvirt_domain" "vm" {
  for_each    = var.namen
  name        = each.key
  type        = "kvm"
  memory      = 768
  memory_unit = "MiB"
  vcpu        = 1
  running     = true

  os = {
    type         = "hvm"
    type_arch    = "x86_64"
    type_machine = "q35"
  }

  cpu = {
    mode = "host-passthrough"
  }

  devices = {
    disks = [
      {
        source = {
          file = { file = libvirt_volume.platte[each.key].path }
        }
        target = { bus = "virtio", dev = "vda" }
        driver = { type = "qcow2" }
      },
      {
        device = "cdrom"
        source = {
          file = { file = libvirt_volume.seed[each.key].path }
        }
        target = { bus = "sata", dev = "sda" }
      }
    ]
    interfaces = [
      {
        type   = "network"
        model  = { type = "virtio" }
        source = { network = { network = "default" } }
      }
    ]
    consoles = [
      {
        type   = "pty"
        target = { type = "serial", port = 0 }
      }
    ]
  }
}
EOF
  • for_each = var.namen erzeugt jede Ressource einmal pro Name. each.key ist der Name.
  • capacity ist in Bytes, memory mit memory_unit = "MiB" in MiB.
  • libvirt_cloudinit_disk baut die ISO lokal, libvirt_volume.seed lädt sie in den Pool hoch, wie virt-install in Tag 11.

Eine zweite Datei fragt die Adressen ab:

cat > ausgabe.tf <<'EOF'
data "libvirt_domain_interface_addresses" "ip" {
  for_each = libvirt_domain.vm
  domain   = each.value.name
  source   = "lease"
}

output "adressen" {
  value = {
    for name, d in data.libvirt_domain_interface_addresses.ip :
    name => try(d.interfaces[0].addrs[0].addr, "noch keine")
  }
}
EOF

Fortschritt speichern? Kostenlos registrieren

Drill 3: init, plan, apply

tofu init

Erwartet (gekürzt):

Initializing the backend...

Initializing provider plugins...
- Finding dmacvicar/libvirt versions matching "0.9.9"...
- Installing dmacvicar/libvirt v0.9.9...
- Installed dmacvicar/libvirt v0.9.9. Signature validation was skipped due to the registry not containing GPG keys for this provider
…

Achtung: Die Signatur des Providers wird nicht geprüft. Die feste Version 0.9.9 und die Datei .terraform.lock.hcl mit den Prüfsummen sorgen dafür, dass jeder Lauf genau diesen Build bekommt. Die Datei gehört ins Git.

tofu plan | grep -E "^Plan:|will be created"

Erwartet:

  # libvirt_cloudinit_disk.seed["tofu1"] will be created
  # libvirt_cloudinit_disk.seed["tofu2"] will be created
  # libvirt_domain.vm["tofu1"] will be created
  # libvirt_domain.vm["tofu2"] will be created
  # libvirt_volume.platte["tofu1"] will be created
  # libvirt_volume.platte["tofu2"] will be created
  # libvirt_volume.seed["tofu1"] will be created
  # libvirt_volume.seed["tofu2"] will be created
Plan: 8 to add, 0 to change, 0 to destroy.
tofu apply -auto-approve

Erwartet (gekürzt):

…
Outputs:

adressen = {
  "tofu1" = "noch keine"
  "tofu2" = "noch keine"
}

Ausprobiert: Mit dem Beispiel aus der Provider-Doku, also source = { volume = { pool = …, volume = … } }, scheiterte der Start mit Could not open '/var/lib/libvirt/images/basis/noble.qcow2': Permission denied, obwohl die Datei für alle lesbar ist. Die Domain bekommt dann Platten vom Typ volume. Mit virt-xml auf type='file' umgestellt, startete dieselbe Platte, und der Fehler wanderte zum Seed-ISO, die noch volume war. Mit dem Dateipfad (source = { file = … }) entsteht type='file' wie bei virt-install, und beide VMs starten.

Die VMs laufen, haben aber noch keinen Lease. Eine Minute später holt ein zweites apply die Adressen nach, ohne etwas zu ändern:

tofu apply -auto-approve
tofu output adressen

Erwartet (deine Adressen weichen ab):

…
adressen = {
  "tofu1" = "192.168.122.114"
  "tofu2" = "192.168.122.152"
}
ssh [email protected] "hostname; cloud-init status --wait | tail -1"

Erwartet (nach der Bestätigung des Hostschlüssels):

tofu1
status: done

Fortschritt speichern? Kostenlos registrieren

Drill 4: Abweichungen

Was, wenn jemand an OpenTofu vorbei ändert?

virsh setmaxmem tofu1 1G --config
tofu plan | tail -1

Erwartet:

No changes. Your infrastructure matches the configuration.

Ausprobiert: Der Provider 0.9.9 bemerkt den geänderten Speicher nicht. Er vergleicht nicht jedes Feld der Domain-XML mit dem Sollwert. Erkannt hat er im Test nur, dass die VM nicht mehr lief.

virsh shutdown tofu1

Wenn tofu1 aus ist:

tofu plan | grep -E "^\s+~ |^Plan:"

Erwartet:

  ~ resource "libvirt_domain" "vm" {
      ~ running     = false -> true
Plan: 0 to add, 1 to change, 0 to destroy.

apply würde tofu1 starten, aber mit 1 GiB Obergrenze statt 768 MiB. Den Sollzustand erzwingt ein Austausch:

tofu apply -auto-approve \
  -replace='libvirt_domain.vm["tofu1"]' | grep -E "replace|^Apply"
virsh dumpxml tofu1 --inactive | grep "<memory"

Erwartet:

-/+ destroy and then create replacement
  # libvirt_domain.vm["tofu1"] will be replaced, as requested
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
  <memory unit='KiB'>786432</memory>

Nur die Domain wird ersetzt. Die Platte ist eine eigene Ressource und bleibt mit ihrem Inhalt erhalten.

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

tofu state list | wc -l

Erwartet: 10 (8 Ressourcen und 2 Einträge der Data Source ip).

virsh list | grep tofu

Erwartet: tofu1 und tofu2, beide running.

tofu plan | tail -1

Erwartet: No changes. Your infrastructure matches the configuration.

Challenge

tofu2 wird nicht mehr gebraucht. Entferne sie, ohne main.tf zu ändern und ohne tofu1 anzufassen. Baue danach alles ab und prüfe, dass das Basis-Image noch da ist.

Hinweis: Variablen lassen sich mit -var überschreiben.

Lösung

tofu plan -var 'namen=["tofu1"]' | grep -E "will be destroyed|^Plan:"

Erwartet:

  # libvirt_cloudinit_disk.seed["tofu2"] will be destroyed
  # libvirt_domain.vm["tofu2"] will be destroyed
  # libvirt_volume.platte["tofu2"] will be destroyed
  # libvirt_volume.seed["tofu2"] will be destroyed
Plan: 0 to add, 0 to change, 4 to destroy.
tofu apply -auto-approve -var 'namen=["tofu1"]' | grep "^Apply"
virsh list --all | grep tofu

Erwartet:

Apply complete! Resources: 0 added, 0 changed, 4 destroyed.
 34   tofu1   running

Und alles weg:

tofu destroy -auto-approve | grep "^Destroy"
virsh list --all | grep -c tofu
sudo ls /var/lib/libvirt/images/basis/

Erwartet:

Destroy complete! Resources: 4 destroyed.
0
noble.qcow2

Das Basis-Image war nie Teil des States. OpenTofu löscht nur, was es selbst angelegt hat.

Fortschritt speichern? Kostenlos registrieren

Enterprise-Notiz

  • State gehört nicht auf den Laptop: Im Team liegt er in einem Backend mit Sperre (S3 mit Lockfile, HTTP-Backend von GitLab). OpenTofu kann den State verschlüsseln (encryption-Block).
  • Provider-Reife: Der libvirt-Provider ist ein Gemeinschaftsprojekt mit einem Hauptautor. Die Version 0.9 hat das Schema komplett geändert. Wer darauf baut, pinnt die Version und testet Updates in einem Lab wie diesem.
  • Größere Umgebungen: Für Proxmox gibt es den Provider bpg/proxmox, für OpenStack und OpenNebula offizielle Provider. Dort lohnt OpenTofu mehr als für einzelne libvirt-Hosts.
  • Mehrere Hosts: Ein Provider-Block mit alias und uri = "qemu+ssh://ubuntu@kvm2/system" steuert kvm2 aus derselben Konfiguration.