Terraform Count and for_each
Get a quick overview of Terraform count and for_each so you can choose the right repetition pattern before learning each meta-argument in detail.
As Terraform configurations grow, you quickly reach a common problem: you need to create multiple similar resources without copy-pasting the same block again and again. Terraform solves that with two important meta-arguments: count and for_each.
Both let you declare one resource block and expand it into multiple instances, but they are best at different kinds of repetition.
| Meta-argument | Use case |
|---|---|
| count | Simple numeric repetition |
| for_each | Map/set-based iteration with named instances |
Use count when your main question is, "How many copies do I need?" It works well for patterns like creating three identical EC2 instances or optionally creating one resource when a boolean is true.
Use for_each when your instances have stable identities, such as environment names, bucket names, or per-team settings. Because each instance is keyed by name rather than list position, for_each is usually safer when the collection may change over time.
A practical rule is:
- choose
countfor simple, index-based repetition - choose
for_eachfor named items and long-lived infrastructure
Another way to think about the difference is that count answers a quantity question, while for_each answers an identity question. If your design starts with "I need three of these," count is often the cleanest tool. If your design starts with "I need one for dev, one for staging, and one for prod," for_each usually maps better to the real infrastructure.
In the next lessons, you will learn both patterns in depth, including syntax, references, tradeoffs, and common pitfalls.