Sample Header Ad - 728x90

terraform resource dependency with count(loop)

0 votes
1 answer
38 views
I'm trying to create stack of multiple vms on KVM_HOST with terraform. The catch is, I'm using pxeboot & kickstart to do installation. Kickstart file needs to carry some dynamic information, like static IPs, hostname etc, therefore I have to create it for each vm, and this kickstart file needs to stay there till vm reads it & starts installation. Then next kickstart file is created for vm 2, and it needs to stay there till vm2 reads it for installation. So there should be some delay in creating these resources, either with loop or depend_on parameter, but what I'm getting is, kickstart files for all vms are generated right away, last one is overriding, of course, so correct info is not passed. here's two resources which I need to loop in sequence for number of variable value qty
variable "vm_count" {
  type    = number
  default = 1
}
below are resources
resource "null_resource" "delay" {
  count = var.vm_count

  provisioner "local-exec" {
    command = "sleep 150"
  }
  depends_on = [libvirt_domain.vm]
}

resource "local_file" "kickstart_file" {
  count = var.vm_count
  content = templatefile("ks.tpl", {
    ip                = "192.168.1.${117 + count.index}"
    netmask           = var.netmask
    gateway           = var.gateway
    dns               = var.dns
    hostname          = "${var.hostname}-${count.index + 1}"
    disk_size_rounded = ((var.disk_size - 1) * 1024) -1
  })
  filename = "/var/www/html/kickstart/ks-terraform.cfg"
}

resource "libvirt_domain" "vm" {
  count  = var.vm_count
  name   = "${var.hostname}-${count.index + 1}"
  memory = var.memory
  vcpu   = var.cpu
  arch   = "x86_64"

  cpu {
    mode = "host-passthrough"
  }

  boot_device {
    dev = ["hd", "network"]
  }

  disk {
    volume_id = libvirt_volume.default_disk[count.index].id
  }

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

  network_interface {
    bridge = "virbr0"
    macvtap  = false
  }

  depends_on = [local_file.kickstart_file, null_resource.delay]
}
how can I improve the logic with depends on or for_each?
Asked by Sollosa (1993 rep)
Feb 11, 2025, 02:11 PM
Last activity: Feb 11, 2025, 07:18 PM