Search code examples
terraform

Getting domain IPs when using Libvirt Terraform provider


I'm creating a couple of instances through Teraform using the libvirt provider as below:

resource "libvirt_domain" "node" {
  for_each  = { for idx, vm_name in var.kvm_names: vm_name => idx}
  name      = format("%s", each.key)
  vcpu      = var.vcpu
  memory    = var.memoryMB
  cloudinit = libvirt_cloudinit_disk.commoninit[each.key].id

  disk {
    volume_id = "${libvirt_volume.image[each.key].id}"
  }

  network_interface {
    network_name = "default"
  }

   network_interface {
     network_id = libvirt_network.test_network.id
     network_name = libvirt_network.test_network.name
  }
}

If I try to output the IPs (I'd like to use them to pass them to Ansible to do some configs) it spits out this error:

outputting code:

output "ips" {
    value = "${libvirt_domain.node[*].network_interface[*].addresses[0]}"
}

│ Error: Unsupported attribute │ │ on kvm.tf line 66, in output "ips": │ 66: value = "${libvirt_domain.node[]..network_interface[*].addresses[0]}" │ │ This object does not have an attribute named "network_interface".

If I use the below it works:

output "ips" {
    value = "${libvirt_domain.node[*]}"
}

and I can see the interface attribute as expected. How can I get and use the network interface IPs from my VMs?


Solution

  • Since you are using for_each to create the resource, that means the resource will have key-value pairs when trying to fetch the attributes. I would expect something like the following to work:

    output "ips" {
        value = values(libvirt_domain.node)[*].network_interface.*.addresses[0]
    }
    

    The values built-in function is fetching all the values for all the keys, with the addition that the wanted attributes can be specified to filter out the output.