Count and For Each
The count and for_each meta-arguments create multiple instances of a resource or module from one block. Count makes numbered copies, while for_each makes one instance per item in a map or set, addressed by a stable key.
What Are Count and For Each?
count takes a number and addresses copies as [0], [1], and so on. for_each takes a map or a set of strings and addresses each copy by its key, such as ["kyc"].
resource "aws_s3_bucket" "domain_data" { for_each = toset(["orders", "payments", "kyc"]) bucket = "shopify-${each.value}-data-prod"}When to Use Which
| Situation | Use |
|---|---|
| Identical, interchangeable copies | count |
| Items with meaningful names | for_each |
| Create zero or one conditionally | count = var.enabled ? 1 : 0 |
Common MistakeDriving
countfrom a list and removing a middle item. Later indexes shift, so Terraform plans to recreate them. Usefor_each, and use amovedblock when converting an existing resource.
Frequently Asked Questions
Why is for_each safer than count when the list changes?
Count identifies instances by position, so removing a middle item renumbers the rest. For_each identifies them by key, so only the removed key is affected.
Can I pass a list to for_each?
Not directly. Convert it with toset(). for_each also needs keys known at plan time.