Terraform count vs for_each
count creates indexed copies (aws_instance.web[0], [1], [2]). for_each creates named resources by key (aws_instance.web["dev"], ["prod"]). Production rule: use count for identical copies, for_each for named/environment resources because changing list ORDER with count destroys and recreates resources — for_each uses stable keys, safer for production.
Overview
Two ways to make many instances
Both count and for_each create multiple instances of a resource or module. They differ in how they identify each instance, and that difference has major production safety implications. With count, which takes a number, each instance gets a positional index, such as web[0], web[1] and web[2]. With for_each, which takes a map or a set, each instance gets a stable key, such as web[dev], web[test] and web[prod].
Key concepts
- count.index
- each.key / each.value
- toset()
- Resource address
- Index stability
Interview questions
- Why is for_each safer than count for production resources?
Sign up free to read the full topic
More DevOps topics
- Storage Errors — FailedMount, Pending PVCs, Multi-Attach and Full Volumes
- Strangler Fig
- Team Topologies
- Tekton
- Terraform — Production Errors, Mistakes and Recovery
- Terraform & OpenTofu
- Terraform Essentials — Plan and Apply, Variables, Outputs, Data Sources, and Sharing State at Scale
- Terraform in CI/CD Pipelines
- Terraform Remote State — S3 + DynamoDB
- Test Pyramid
- The C/C++ Compilation Model
- The flux CLI
Start free on Cariara · Coding problems · System design studio