迭代 Terraform 模板文件中的多个输出

Iterate over multiple outputs in Terraform template file

我正在尝试使用 Terraform 按以下格式创建 Ansible 清单文件

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 模板文件:

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

以上产生

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

而不是

10.1.0.14 #vm1
10.1.0.7 #vm2

关于如何正确迭代两个输出有什么建议吗?

您应该改为创建映射或元组列表,这样虚拟机名称和 IP 就会关联起来。

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

然后在您的模板中:

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

这将按预期呈现

10.1.0.14 #vm1
10.1.0.7 #vm2