Interview Prep/Terraform/Resources Variables and Expressions

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 →

  1. Show the for version with named keys.
  2. 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.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions