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.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerA security group needs 15 ingress rules read from a variable. How do you avoid 15 copy-pasted blocks?Intermediate