Terraform 列表元素越界?
Terraform list element out of bounds?
来自 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: return None/Nil
- Java/JS/Ruby: 引发错误
我已经习惯了它们,它们似乎很有道理,你要么什么也得不到,要么会出错,但你为什么会期望得到列表中的 k mod n
元素?如果您是实施者,您将如何证明这种行为选择的合理性。
这是一个必须自己执行 mod 的快捷方式,但在循环遍历一个简短列表(例如要在其中放置多个实例的子网或可用性区域的数量)时非常有用。
这是一个很常见的模式,出现在 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,只要实例数多于数据源返回的子网数,就会出现索引越界异常。
来自 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: return None/Nil
- Java/JS/Ruby: 引发错误
我已经习惯了它们,它们似乎很有道理,你要么什么也得不到,要么会出错,但你为什么会期望得到列表中的 k mod n
元素?如果您是实施者,您将如何证明这种行为选择的合理性。
这是一个必须自己执行 mod 的快捷方式,但在循环遍历一个简短列表(例如要在其中放置多个实例的子网或可用性区域的数量)时非常有用。
这是一个很常见的模式,出现在 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,只要实例数多于数据源返回的子网数,就会出现索引越界异常。