如何输出使用count的数据源?

时间:2018-12-02 22:10:48

标签: terraform

我要输出创建的每个VM及其UUID,例如

data "vsphere_virtual_machine" "vms" {
  count            = "${length(var.vm_names)}"
  name             = "${var.vm_names[count.index]}"
  datacenter_id = "12345"
}

output "vm_to_uuid" {
  # value = "${data.vsphere_virtual_machine.newvms[count.index].name}"
  value = "${data.vsphere_virtual_machine.newvms[count.index].id}"
}

我正在寻找的示例输出:

"vm_to_uuids":[
    {
      "name":"node1",
      "id":"123456",
    },
    {
      "name":"node2",
      "id":"987654",
    }
]

2 个答案:

答案 0 :(得分:3)

在为输出 value 给出的表达式中使用通配符属性,以获取创建的VM的ID列表。 例如

output "vm_to_uuids" {
  value = "${data.vsphere_virtual_machine.*.id}"
}

问题中提供的必需语法是一种豁免,在该豁免中,功能而不是形式。 编写提供该功能的te​​rraform配置并不简单。 也许,我建议采用其他更简单的方法来输出相同的信息。

可以输出映射到ID的名称:

output "vm_to_uuids" {
  value = "${zipmap(
              data.vsphere_virtual_machine.*.name,
              data.vsphere_virtual_machine.*.id)}"
}

名称和ID的映射可以按列方式输出:

output "vm_to_uuids" {
  value = "${map("name",
              data.vsphere_virtual_machine.*.name,
              "id",
              data.vsphere_virtual_machine.*.id)}"
}

可以按列方式输出名称和ID列表:

output "vm_to_uuids" {
  value = "${list(
              data.vsphere_virtual_machine.*.name,
              data.vsphere_virtual_machine.*.id)}"
}

答案 1 :(得分:1)

您可以做的一件事(如果您确实想要该输出),请使用formatlist(format, args, ...)

data "vsphere_virtual_machine" "vms" {
    count            = "${length(var.vm_names)}"
    name             = "${var.vm_names[count.index]}"
    datacenter_id = "12345"
}

output "vm_to_uuid" {
    value = "${join(",", formatlist("{\"name\": \"%s\", \"id\": \"%s\"}", data.vsphere_virtual_machine.newvms.*.name, data.vsphere_virtual_machine.newvms.*.id))}"   
}

还没有测试代码,但是您知道了。尤其是引号转义只是一个猜测,但是很容易从这里弄清楚。

会发生什么情况,您需要获取两个列表(名称和ID)并格式化每个条目中的字典字符串,然后使用逗号分隔将它们连接在一起。

相关问题