Interview Prep/Terraform/Resources Variables and Expressions

A list of resources was created with `count`, and now the team wants `for_each` with no downtime or recreation. How?

AdvancedScenarioResources Variables and Expressions
Answer

Situation read → Changing the repetition mechanism changes state addresses from [0] to ["key"].

What I'd do →

  1. Change the code to for_each.
  2. Declare a moved block for each old index.
  3. Run terraform plan and confirm it shows moves, not destroy/create.
moved {
  from = aws_instance.web[0]
  to   = aws_instance.web["api"]
}
moved {
  from = aws_instance.web[1]
  to   = aws_instance.web["worker"]
}

Why → moved records the rename in code, so every environment performs the same state migration safely when it applies.

Interview tip → terraform state mv does the same but is manual and unreviewable.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions