Interview Prep/Terraform/Resources Variables and Expressions

You have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?

AdvancedScenarioResources Variables and Expressions
Answer

Situation read → for_each needs a flat map, but data is nested.

What I'd do → Flatten with a for expression and build composite keys.

locals {
  subnet_list = flatten([
    for vpc_name, vpc in var.vpcs : [
      for sn_name, sn in vpc.subnets : {
        key  = "${vpc_name}/${sn_name}"
        vpc  = vpc_name
        cidr = sn.cidr
      }
    ]
  ])
  subnet_map = { for s in local.subnet_list : s.key => s }
}

resource "aws_subnet" "this" {
  for_each   = local.subnet_map
  vpc_id     = aws_vpc.this[each.value.vpc].id
  cidr_block = each.value.cidr
}

Why → Composite string keys are stable, human-readable in state (aws_subnet.this["prod/web"]), and make diffs predictable.

Interview tip → Avoid keys that include values known only after apply.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions