How to take the reference of multiple subnets in route_table_association in Terraform?

278 views Asked by At
resource "aws_subnet" "VPC_Public_Subnets" {
vpc_id = aws_vpc.Oracle_VPC_TF_Block.id
for_each = local.subnets.public

availability_zone = each.value.zone
cidr_block = each.value.cidr

tags = {
  Name = each.value.name
  Tier = each.value.tier
} 

}

This is how created the subnets. This block is creating 2 subnets. Now, I want the subnet_id of each of the 2 subnets that will be used in route_table_association.

resource "aws_route_table_association" "Private_Route_Table_App1_Db1_Association" {
  subnet_id = aws_subnet.VPC_Public_Subnets.id
  route_table_id = aws_route_table.Private_Route_Table_App1_Db1.id
}

Now, the problem is what we will the value of subnet_id. Can anyone help me on this?

1

There are 1 answers

3
Marcin On

Since you've used for_each for subnets, you have to use it for route table associations as well:

resource "aws_route_table_association" "Private_Route_Table_App1_Db1_Association" {
  for_each  = aws_subnet.VPC_Public_Subnets
  subnet_id = each.value.id
  route_table_id = aws_route_table.Private_Route_Table_App1_Db1.id
}