我有以下对象变量列表:
variable "objects" {
type = "list"
description = "list of objects
default = [
{
id = "name1"
attribute = "a"
},
{
id = "name2"
attribute = "a,b"
},
{
id = "name3"
attribute = "d"
}
]
}
如何获取id =“ name2”的元素?
答案 0 :(得分:4)
您不能嵌套多个级别的方括号以在数据结构中获取n个级别。但是,您可以使用插值功能来检索此类值。在这种情况下,您将要使用查找功能从地图上检索值,该值本身已经用方括号访问了,看起来像这样...
${lookup(var.objects[1], "id")}
Rowan是正确的,在当前版本的Terraform中难以使用复杂的数据结构。但是,看起来可以很快就可以在这一领域获得更好的支持。即将发布的0.12版本将rich types添加对列表和地图的改进。
答案 1 :(得分:3)
如果您要从IP和主机名列表中创建一组vsphere_virtual_machine
resources,我可以尝试以下方法:
resource "vsphere_virtual_machine" "vm" {
count = "${length(var.virtual_machine_ips)}"
// the rest of your virtual machine config
// such as template ID, CPUs, memory, disks...
vapp {
properties {
// your vApp properties may vary based on what your template actually is.
// these examples are for the CoreOS template.
"guestinfo.hostname" = "${index(var.virtual_machine_hostnames, count.index)}"
"guestinfo.interface.0.ip.0.address" = "${index(var.virtual_machine_ips, count.index)}"
}
}
}
(这是假设您通过vApp config设置IP和主机名;如果不是,则外观可能相似,但是将主机名和IP地址放在vsphere_virtual_machine.vapp.properties
块之外。)
terraform.tfvars
文件可能如下所示:
virtual_machine_ips = ["10.0.2.2", "10.0.2.3", "10.0.2.4"]
virtual_machine_hostnames = ["banana", "pineapple", "coconut"]
这是一种更简单,更惯用的方式来完成您要执行的操作,因为使用Terraform插值语法处理复杂的对象并不容易。
答案 2 :(得分:0)
您将获得具有以下表达式的id =“ name2”的地图:
var.objects[index(var.objects.*.id, "name2")]
要进行快速测试,请在terraform控制台中运行以下单行代码:
[{id = "name1", attribute = "a"}, {id = "name2", attribute = "a,b"}, {id = "name3", attribute = "d"}][index([{id = "name1", attribute = "a"}, {id = "name2", attribute = "a,b"}, {id = "name3", attribute = "d"}].*.id, "name2")]