Search code examples
for-loopansibleterraformansible-inventoryterraform-template-file

Iterate over multiple outputs in Terraform template file


I am trying to create a Ansible inventory file with Terraform in the following format

10.10.10.10  #test-vm

output.tf:

output "vm_name" {
  value = toset([
    for vm_names in azurerm_linux_virtual_machine.vm : vm_names.name
  ])
}

output "vm_ips" {
  value = toset([
    for vm_ips in azurerm_linux_virtual_machine.vm : vm_ips.private_ip_address  ])
}

Terraform template file:

%{ for vm in vm_ips}:
%{for vm in vm_names ~}:
${mc} ${mc_name}
%{ endfor ~}
%{ endfor ~}

The above produces

10.1.0.14 #vm1
10.1.0.14 #vm2
10.1.0.7 #vm1
10.1.0.7 #vm2

Instead of

10.1.0.14 #vm1
10.1.0.7 #vm2

Any suggestion how to iterate over two outputs correctly?


Solution

  • You should create a list of map or tuple instead, so virtual machines names and IPs are linked.

    output "vms" {
      value = [for vm in azurerm_linux_virtual_machine.vm : {
        name = vm.name, 
        ip = vm.private_ip_address 
      }]
    }
    

    Then in your template:

    %{ for vm in vms ~}
    ${vm.ip} #${vm.name}
    %{ endfor ~}
    

    This would renders in the expected

    10.1.0.14 #vm1
    10.1.0.7 #vm2