Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Terraform: referencing resources created using a map of objects variable

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading