Terraform list element out of bounds?

柔情痞子 提交于 2019-12-11 05:11:22

问题


From the Terraform docs:

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.

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: return None/Nil
  • Java/JS/Ruby: Raise an error

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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/51332312/terraform-list-element-out-of-bounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!