title: Terraform For_Each: How to reference created resource ID
body: <p>I created a module that creates AWS subnets. Within the module, I use a for_each loop to create the subnets.  I assumed I could index a given subnet's resource ID, but it seems that the loop does not output index the subnet IDs in the predictable order... Not sure what I am missing here. Any help is appreciated!</p>
  <p><strong>main.tf</strong></p>
  <pre><code>module &quot;subnets&quot; {
    source = &quot;./modules/subnets/&quot;
    vpc_id = aws_vpc.main.id
    subnets = [
      {
        name              = &quot;private-1a&quot;
        cidr_block        = &quot;10.0.0.0/28&quot;
        availability_zone = &quot;us-east-1a&quot;
      },
      {
        name              = &quot;private-1b&quot;
        cidr_block        = &quot;10.0.1.0/24&quot;
        availability_zone = &quot;us-east-1b&quot;
      },
      {
        name              = &quot;public-1a&quot;
        cidr_block        = &quot;10.0.2.0/24&quot;
        availability_zone = &quot;us-east-1a&quot;
      },
      {
        name              = &quot;public-1b&quot;
        cidr_block        = &quot;10.0.3.0/24&quot;
        availability_zone = &quot;us-east-1b&quot;
      }
    ]
  }
  
  
  output &quot;private1a&quot; {
    value = module.security_subnets.subnet_id[0]
  } 
  output &quot;private1b&quot; {
    value = module.security_subnets.subnet_id[1]
  } 
  output &quot;public1a&quot; {
    value = module.security_subnets.subnet_id[2]
  } 
  output &quot;public1b&quot; {
    value = module.security_subnets.subnet_id[3]
  } 
  
  </code></pre>
  <p><strong>module</strong></p>
  <pre><code>locals {
    subnets = {
      for i in var.subnets :
      i.name =&gt; i
    }
  }
  
  resource &quot;aws_subnet&quot; &quot;main&quot; {
    for_each          = local.subnets
    vpc_id            = var.vpc_id
    cidr_block        = each.value.cidr_block
    availability_zone = each.value.availability_zone
  
    tags = merge(
      {
        &quot;Name&quot; = format(&quot;%s&quot;, each.value.name)
      }
    )
  
  }
  
  output subnet_id {
    value = values(aws_subnet.main)[*].id
  }
  
  </code></pre>