Terraform offers two resource repetition mechanisms: count
and for_each
. The main difference between these is how Terraform will track the multiple instances they create:
- When using
count
, each of the multiple instances is tracked by a number starting at 0, giving addresses like aws_vpc.vpc[0]
and aws_vpc.vpc[1]
.
- When using
for_each
, each of the multiple instances is tracked by a string which could be obtained either from a key in a map or from an element in a set, giving addresses like aws_vpc.vpc["10.0.0.0/16"]
and aws_vpc.vpc["10.1.0.0/16"]
.
The most common reason to choose for_each
rather than count
is to ensure that the order of whatever collection of values is driving the repetition is not significant. In your specific case, that would produce the same result regardless of whether var.vpc_cidrs
is ["10.0.0.0/16", "10.1.0.0/16"]
or ["10.1.0.0/16", "10.0.0.0/16"]
, because the instances would be tracked by the CIDR block string and the index in the list is totally ignored.
With that all said, the reason why the index isn't directly available when using for_each
is that this would defeat the main purpose of using for_each
: it would make the order significant again. In your specific situation, if you used the index in the tag Name then changing the order of the list would cause Terraform to plan to swap the tagging on those two VPCs:
# aws_vpc.vpc["10.0.0.0/16"] will be updated in-place
~ resource "aws_vpc" "vpc" {
~ tags = {
~ Name = "Company01" -> "Company02"
}
# ...
}
# aws_vpc.vpc["10.0.0.0/16"] will be updated in-place
~ resource "aws_vpc" "vpc" {
~ tags = {
~ Name = "Company02" -> "Company01"
}
# ...
}
Perhaps that is fine for your case, if those numbers are just there to create some uniqueness and it doesn't matter if they get reassigned over time as CIDR blocks are added, removed and reordered in the input variable. If that's true, then we can derive a value that contains the original index and use that as part of for_each
like this:
resource "aws_vpc" "vpc" {
for_each = { for i, b in var.vpc_cidrs : b => { index = i } }
cidr_block = each.key
tags = {
Name = format("Company%02d", each.value.index + 1)
}
}
If you consider the position in the list to be truly significant though -- for example, if you'd want swapping two elements in the list to change the cidr_block
values on the two existing objects rather than to re-tag them, it would be more appropriate to use count
so that Terraform tracks them by the indices itself:
resource "aws_vpc" "vpc" {
count = length(var.vpc_cidrs)
cidr_block = var.vpc_cidrs[count.index]
tags = {
Name = format("Company%02d", count.index + 1)
}
}