indexing - Terraform 列表元素超出范围?

标签 indexing indexoutofboundsexception terraform

来自 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/

相关文章:

mongodb - Mongoose/mongoDB 删除唯一索引约束

java - 重用 StringBuilder 和 ArrayIndexOutOfBoundsException

java - 索引越界异常: getting same row repeated several times

amazon-web-services - terraform 后端 s3 存储桶创建返回 403 w/Terraform 0.11.1

python - 分配给 pandas DataFrame 中的新列时令人费解的 KeyError

python - 如何自定义数据帧索引,同时保持它们自动递增?

sql - 综合指数如何运作?

java.lang.ArrayIndexOutOfBoundsException : 0 (stack implementation) 异常

azure - 如何在 terraform 中的 AKS 群集资源创建的虚拟机规模集或负载均衡器上启用诊断日志?

amazon-web-services - terraform 如何找到在模块上创建的存储桶的 ARN