A reviewer asks why you use `locals` with `for` expressions instead of `count` and `element()`. How do you answer?
IntermediateScenarioResources Variables and Expressions
Answer
Situation read → A style discussion about readability and safety.
What I'd do →
- Show the
forversion with named keys. - Compare with
element(var.list, count.index)patterns.
locals {
buckets = { for env in var.envs : env => "${var.project}-${env}" }
}
resource "aws_s3_bucket" "this" {
for_each = local.buckets
bucket = each.value
}
Why → for expressions are explicit and keyed, so changes are local and plans are readable. Index arithmetic hides intent and breaks when order changes.
Interview tip → Prefer data shapes that match how people refer to things (names), not positions.
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?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?Advanced