如何从 Terraform 中的对象列表中获取对象? [英] How to get an object from a list of objects in Terraform?
问题描述
我有以下对象变量列表:
I have the following list of objects variable:
variable "objects" {
type = "list"
description = "list of objects
default = [
{
id = "name1"
attribute = "a"
},
{
id = "name2"
attribute = "a,b"
},
{
id = "name3"
attribute = "d"
}
]
}
如何获取 id = "name2" 的元素?
How do I get element with id = "name2" ?
推荐答案
如果你想创建一组 vsphere_virtual_machine
resources 来自 IP 和主机名列表,我可以试试这个:
If you're looking to create a set of vsphere_virtual_machine
resources from a list of IPs and hostnames, I might try this:
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 地址放在 vsphere_virtual_machine.vapp.properties 之外的某个位置
块.)
(This is assuming that you are setting IP and hostname via vApp config; if not then it may look similar but put the hostname and IP addresses somewhere outside the vsphere_virtual_machine.vapp.properties
block.)
terraform.tfvars
文件可能如下所示:
virtual_machine_ips = ["10.0.2.2", "10.0.2.3", "10.0.2.4"]
virtual_machine_hostnames = ["banana", "pineapple", "coconut"]
这是一种更简单、更惯用的方式来完成您正在尝试做的事情,因为在 Terraform 插值语法中处理复杂对象并不容易.
This is a simpler and more idiomatic way of accomplishing what you're trying to do, since working with complex objects in Terraform interpolation syntax is not easy.
这篇关于如何从 Terraform 中的对象列表中获取对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!