0.12 and aws_route_table_associations

I have created 3 subnets with the for_each syntax e.g.

resource "aws_subnet" "subnet" {
	for_each   = var.subnet_cidrs
	vpc_id     = aws_vpc.main.id
	cidr_block = each.value
	availability_zone = each.key
}

I now want to associate these with a route table, in past Terraform versions I could do

resource "aws_route_table_association" "public_route_assoc" {
  count          = length (var.subnet_cidrs)
  subnet_id      = element(aws_subnet.subnet.*.id, count.index)
  route_table_id = element(aws_route_table.public_route.*.id, count.index)
}

but this doesn’t seem to work in 0.12 and I can’t work out the syntax for it. Is it still possible to do this in 0.12?

Thanks!

1 Like

Syntax is a bit different. Have a look here: https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9

Why don’t you use for_each in the association resource as well?

If you look at the subnets created, they should have availability zones as identifier and not be numbered 0…n.

Try defining an output with value= aws_subnet.subnet and look at that, it should be a map and not a list

So something like
resource “aws_route_table_association” “public_route_assoc” {
for_each = var.subnet_cidrs
subnet_id = aws_subnet.subnet.[each.key].id
route_table_id = aws_route_table.public_route.[each.key].id
}

… assuming that you created the route tables using the same for_each as the subnets

Hope this helps, I don’t have my AWS account handy so I’m just improvising here

1 Like