Home > database >  for_each and count expressions in Terraform
for_each and count expressions in Terraform

Time:05-05

I'm trying to study Terraform. I have subnets, that are created with "for_each" expression.

variable "privateSubnetCIDR" {
  type = list(string)
  default = ["10.0.10.0/24","10.0.20.0/24"]
}
resource "aws_subnet" "privatesubnet" {
  for_each                = toset(var.privateSubnetCIDR)
  cidr_block              = each.key
  vpc_id                  = aws_vpc.dev_vpc.id
  map_public_ip_on_launch = false
  availability_zone       = element(data.aws_availability_zones.availableAZ.names, index(var.privateSubnetCIDR, each.key))
  tags = {
    name        = "${var.environment}-privatesubnet-${index(var.privateSubnetCIDR, each.key)   1}"
    AZ          = element(data.aws_availability_zones.availableAZ.names, index(var.privateSubnetCIDR, each.key))
    Environment = "${var.environment}-privatesubnet"
  }
}

And I also have NAT routetable, that uses "count".

resource "aws_route_table" "nat_routetable" {
  vpc_id = aws_vpc.dev_vpc.id
  count  = length(var.publicSubnetCIDR)
  route {
    cidr_block = var.route_cidr
    gateway_id = aws_nat_gateway.nat-gateway[count.index].id
  }
  depends_on = [aws_nat_gateway.nat-gateway]
}
resource "aws_route_table_association" "nat_routeTableAssociation" {
  count          = length(var.privateSubnetCIDR)
  route_table_id = aws_route_table.nat_routetable[count.index].id
  subnet_id      = aws_subnet.privatesubnet[count.index].id
}

After terraform plan I get an error on the last string.

│ Error: Invalid index
│ 
│   on modules/network/subnets.tf line 91, in resource "aws_route_table_association" "nat_routeTableAssociation":
│   91:   subnet_id      = aws_subnet.privatesubnet[count.index].id
│     ├────────────────
│     │ aws_subnet.privatesubnet is object with 2 attributes
│     │ count.index is 0
│ 
│ The given key does not identify an element in this collection value. An object only supports looking up attributes by name,
│ not by numeric index.

If I use "count" in subnet definition, all works. But is there any way to use "for_each" in subnet definition and "count" in route_table definition?

CodePudding user response:

You could do that, yes. You need to go via the intermediary var.privateSubnetCIDR though:

aws_subnet.privatesubnet[var.privateSubnetCIDR[count.index]].id

But at that point you should just use a for_each on the aws_route_table_association as well.

  • Related