Terraform列表元素超出范围? [英] Terraform list element out of bounds?

查看:19
本文介绍了Terraform列表元素超出范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Terraform 文档:

From the Terraform docs:

element(list, index) - 从给定索引处的列表中返回单个元素.如果索引大于元素的数量,此函数将使用标准的 mod 算法进行换行.

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 包装的充分理由是什么?在我看来,这种行为可能是导致很多头痛的原因.

What would be a good reason to wrap using mod? This behavior seems to me like it could be the cause of lots of headaches.

在我的脑海中,我只记得另外两种处理访问越界元素的方法:

At the top of my head I can only remember two other approaches to handle accessing an element that's out of bounds:

  • Python/Ruby:返回无/无
  • Java/JS/Ruby:引发错误

我已经习惯了它们,以至于它们似乎很有意义,您要么一无所获,要么出现错误,但为什么您会期望在列表中获得 k mod n 元素?如果您是实施者,您将如何证明这种行为选择的合理性.

I'm so used to them that they seem to make sense, you either get nothing or an error but why would you ever expect to get the k mod n element in the list? If you were the implementer, how would you justify this choice of behavior.

推荐答案

这是一个必须自己做 mod 的捷径,但在循环一个短列表时很有用,比如你想要的子网数量或可用区的数量放入多个实例.

It's a shortcut for having to do the mod yourself but can be useful when looping over a short list such as the amount of subnets or availability zones that you want to put multiple instances in.

这是一种非常常见的模式,出现在 aws_subnet_ids 数据源文档:

This is a pretty common pattern and appears in the 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)}"
}

如果您要使用 切片运算符 相反,只要您的实例多于数据源返回的子网,您就会得到一个索引越界异常.

If you were to use the slice operator instead you would get an index out of bounds exception as soon as you have more instances than subnets returned by the data source.

这篇关于Terraform列表元素超出范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆