locals { output_dir = abspath("${path.module}/../output") cloud_images = try(sort(fileset(local.output_dir, "Parch-Linux-x86_64-cloudimg-*.qcow2")), []) selected_image = var.image_path != "" ? pathexpand(var.image_path) : ( length(local.cloud_images) > 0 ? "${local.output_dir}/${local.cloud_images[length(local.cloud_images) - 1]}" : "" ) ssh_public_key = trimspace(file(pathexpand(var.ssh_public_key_path))) } resource "libvirt_volume" "root" { name = "${var.vm_name}.qcow2" pool = var.libvirt_pool target = { format = { type = "qcow2" } } create = { content = { url = local.selected_image } } lifecycle { precondition { condition = local.selected_image != "" && fileexists(local.selected_image) error_message = "No Parch cloudimg QCOW2 found. Run 'make build' first or set -var image_path=/absolute/path/to/cloudimg.qcow2." } } } resource "libvirt_cloudinit_disk" "seed" { name = "${var.vm_name}-cloudinit" user_data = templatefile("${path.module}/cloud-init/user-data.yaml.tftpl", { hostname = var.vm_name ssh_public_key = jsonencode(local.ssh_public_key) }) meta_data = yamlencode({ instance-id = var.vm_name local-hostname = var.vm_name }) } resource "libvirt_volume" "cloudinit" { name = "${var.vm_name}-cloudinit.iso" pool = var.libvirt_pool target = { format = { type = "iso" } } create = { content = { url = libvirt_cloudinit_disk.seed.path } } } resource "libvirt_domain" "vm" { name = var.vm_name type = "kvm" memory = var.memory_mib memory_unit = "MiB" vcpu = var.vcpu features = { acpi = true apic = {} } cpu = { mode = "host-passthrough" } os = { type = "hvm" type_arch = "x86_64" type_machine = "q35" boot_devices = [{ dev = "hd" }] } devices = { disks = [ { driver = { name = "qemu", type = "qcow2" } source = { volume = { pool = libvirt_volume.root.pool, volume = libvirt_volume.root.name } } target = { dev = "vda", bus = "virtio" } }, { device = "cdrom" source = { volume = { pool = libvirt_volume.cloudinit.pool, volume = libvirt_volume.cloudinit.name } } target = { dev = "sda", bus = "sata" } } ] interfaces = [ { type = "network" model = { type = "virtio" } source = { network = { network = var.libvirt_network } } } ] serials = [{ type = "pty" target = { type = "isa-serial", port = 0 } }] consoles = [{ type = "pty" target = { type = "serial", port = 0 } }] channels = [{ source = { unix = {} } target = { virt_io = { name = "org.qemu.guest_agent.0" } } }] rngs = [{ model = "virtio" backend = { random = "/dev/urandom" } }] } running = true lifecycle { replace_triggered_by = [libvirt_volume.root, libvirt_volume.cloudinit] } } output "vm_name" { value = libvirt_domain.vm.name } output "ssh_command" { value = "make qemu-ssh (or: ssh -o IdentitiesOnly=yes -i ${trimsuffix(pathexpand(var.ssh_public_key_path), ".pub")} arch@)" }