Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

indexing - Terraform list element out of bounds?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...