A deep dive into Terraform's three repetition mechanisms: count, for_each, and dynamic blocks. Explains the index-shift problem that makes count dangerous for list-based resources, how for_each provides stable identity-based addressing, and when dynamic blocks are appropriate for nested configuration. Covers the requirement that for_each keys must be known at plan time, patterns for handling computed Azure values safely, and a step-by-step guide to refactoring from count to for_each using moved blocks without destroying existing Azure infrastructure. Includes practical AzureRM module patterns and a list of common mistakes to avoid.

18m read timeFrom build5nines.com
Post cover image
Table of contents
The Big Difference: Numbers, Keys, and Nested BlocksWhere count Gets Dangerous: The Index-Shift ProblemWhen count Is Still Finefor_each Wants Known Keys Before ApplyHandling Computed Values With for_eachWhy Stable Keys Are Infrastructure DesignDynamic Blocks: Helpful Tool or Readability Trap?Dynamic Blocks vs. Separate ResourcesDebugging Tradeoffs With Dynamic BlocksRefactoring From count to for_each Without Recreating Azure ResourcesA Safer Refactoring WorkflowRefactoring With terraform state mvCommon Mistakes to AvoidPractical Guidance for AzureRM ModulesThe Mental Model That Keeps You SafeConclusion: Prefer Identity Over Position
145 Impressions