Interview Prep/Terraform/Loops, Conditionals, Dynamic Blocks and Functions

When should you choose `for_each` over `count`?

IntermediateConceptLoops, Conditionals, Dynamic Blocks and Functions
Answer

Whenever the instances are distinct things identified by a name. With count, removing an item from the middle of a list shifts every later index, so Terraform wants to destroy and recreate the shifted resources. With for_each, keys are stable, so only the removed key is destroyed. We keep count for simple on/off toggles and truly identical replicas.

All Terraform questions Roadmap: Terraform

More on Loops, Conditionals, Dynamic Blocks and Functions