title: Using for_each in aws_route_table to create routes to subnets in different availability zones
body: <p>I am trying to automate as much as possible with terraform. I am using 2 VPCs (1 application, 1 management). In the 1st VPC (app), I use count to determine the number of availability zones (AZs) in a given region &amp; create subnets for each AZ. That part works. In the 2nd VPC (management), I have 1 subnet that needs to talk to these 3 subnets in VPC1. Basically, I want to automate the creation of aws_route_table to have this:</p>
  <pre><code>VPC2.subnet1 ------&gt; VPC1.subnet1
                  |--&gt; VPC1.subnet2
                   --&gt; VPC1.subnet3
  </code></pre>
  <p>But with my code, I end up having 3 separate aws_route_table resources:</p>
  <pre><code>VPC2.subnet1 ------&gt; VPC1.subnet1
  VPC2.subnet1 ------&gt; VPC1.subnet2
  VPC2.subnet1 ------&gt; VPC1.subnet3
  </code></pre>
  <p>Here's my bad code:
  Getting all the AZs in the region:</p>
  <pre><code>data &quot;aws_availability_zones&quot; &quot;azs&quot; {}
  </code></pre>
  <p>Automatically creating subnets in each AZ using count:</p>
  <pre><code>resource &quot;aws_subnet&quot; &quot;app_public_subnet&quot; {
    count = length(data.aws_availability_zones.azs.names)
  
    vpc_id = aws_vpc.app_vpc.id
    availability_zone = element(data.aws_availability_zones.azs.names, count.index)
    cidr_block = cidrsubnet(var.app_vpc_cidr_block, 8, count.index + 1)
  
    tags = {
      Name = &quot;${var.project}_app_public_subnet_${count.index + 1}&quot;
    }
  }
  </code></pre>
  <p>Trying to create aws_route_table resources using for_each, but the code below creates 3 separate aws_route_table instances, instead of 1 instance with the 3 routes inside. I am new to terraform, I am still learning.</p>
  <pre><code>resource &quot;aws_route_table&quot; &quot;mgmt_rt&quot; {
    vpc_id = aws_vpc.mgmt_vpc.id
  
     for_each = toset(aws_subnet.app_public_subnet[*].cidr_block)
     route {                                                         # Route via VPC peering connection
       cidr_block = each.value
       gateway_id = aws_vpc_peering_connection.mgmt_peer.id
     }
  
    route {
      cidr_block = var.all_cidr
      gateway_id = aws_internet_gateway.mgmt_igw.id
    }
  
    tags = {
      Name = &quot;${var.project}_mgmt_rt&quot;
    }
  }
  
  </code></pre>