来自 Terraform 文档:
element(list, index) - Returns a single element from a list at the given index. If the index is greater than the number of elements, this function will wrap using a standard mod algorithm.
使用 mod 包装的好理由是什么?在我看来,这种行为可能会引起很多头痛。
在我的脑海中,我只记得另外两种处理访问越界元素的方法:
- Python/Ruby:返回 None/Nil
- Java/JS/Ruby:引发错误
我已经习惯了它们,它们似乎很有意义,您要么什么也得不到,要么出现错误,但为什么您会期望在列表中获得 k mod n
元素呢?如果您是实现者,您将如何证明这种行为选择的合理性。
最佳答案
这是必须自己进行修改的快捷方式,但在循环简短列表(例如您想要放入多个实例的子网或可用区域的数量)时非常有用。
这是一种非常常见的模式,出现在 aws_subnet_ids
data source docs 中:
data "aws_subnet_ids" "private" {
vpc_id = "${var.vpc_id}"
tags {
Tier = "Private"
}
}
resource "aws_instance" "app" {
count = 6
ami = "${var.ami}"
instance_type = "t2.micro"
subnet_id = "${element(data.aws_subnet_ids.private.ids, count.index)}"
}
如果您要使用 slice operator相反,只要您的实例数量多于数据源返回的子网数量,您就会收到索引越界异常。
关于indexing - Terraform 列表元素超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51332312/