Chapter Five
Iteration and Conditionals
How Terraform makes many resources from one block, transforms data inline, and branches without an if statement — and why the choice between count and for_each decides what your state churns.
HCL has no for loop and no if statement. What it has instead are meta-arguments that repeat a resource block, expressions that reshape a collection, and a single ternary that branches. This chapter is where you learn to make Terraform produce ten subnets, three IAM roles, or zero of a thing, all from one block that reads cleanly in a plan.
The most consequential decision in the whole course lives here: count versus for_each. Pick wrong and a one-line edit to a list destroys and recreates resources you never touched. The rest — for expressions, the ternary, splat — are the tools that build the exact data structures iteration needs and pull values back out of the results.
Topics in This Chapter
? 1 : 0 conditional-creation idiom, and the renumbering trap that makes index-based identity dangerous.for_each.[*] shorthand for pulling one attribute out of a list of objects, why it doesn't work on a for_each map, and when to reach for a full for instead.