I am a bit new to Terraform and learning. I have the following defined in my varaibles.tf as a map of objects, which will allow me to configure multiple subnets (currently only 1):
variable "subnets" {
type = map(object({name=string, cidr=string, az=string, public=bool}))
default = {
"public_subnet" = {
name="public",
cidr="10.123.1.0/24",
az="us-east-1a",
public=true
}
}
In main.tf i have the following:
resource "aws_subnet" "subnets" {
for_each = var.subnets
vpc_id = aws_vpc.vpc.id
cidr_block = each.value.cidr
availability_zone = each.value.az
map_public_ip_on_launch = each.value.public
tags = {
Name = "${each.value.name}_subnet"
}
}
Now my questions are how would i code the aws_route_table_association and aws_instance to make use of a specific subnet from my varaible map?
Normally if i didnt have a map i would do something like this:
resource "aws_route_table_association" "public_rta" {
subnet_id = aws_subnet.subnet.id
route_table_id = aws_route_table.public_rt.id
}
Im not sure how to references a subnet’s id created in a loop in this case.
>Solution :
For this to work you would have to use for_each with the route table association resource as well (or reference different keys). In the scenario you want all your subnets attached to the same route table, you can use resource chaining with for_each in this case:
resource "aws_subnet" "subnets" {
for_each = var.subnets
vpc_id = aws_vpc.vpc.id
cidr_block = each.value.cidr
availability_zone = each.value.az
map_public_ip_on_launch = each.value.public
tags = {
Name = "${each.value.name}_subnet"
}
resource "aws_route_table_association" "public_rta" {
for_each = aws_subnet.subnets
subnet_id = each.value.id
route_table_id = aws_route_table.public_rt.id
}