问题
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