Interview Prep/Terraform/Resources Variables and Expressions

You 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?

IntermediateScenarioResources Variables and Expressions
Answer

Situation read → count keyed by list index; the list shifted.

What I'd do →

  1. Switch to for_each over a map keyed by a stable name.
  2. Add moved blocks to avoid recreating existing subnets.
variable "subnets" {
  type = map(string)   # { a = "10.0.1.0/24", b = "10.0.2.0/24" }
}
resource "aws_subnet" "this" {
  for_each   = var.subnets
  vpc_id     = aws_vpc.main.id
  cidr_block = each.value
}

Why → Keys are identities. Removing key b only affects b.

Interview tip → Choose keys that never change (names, not IPs).

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions