Skip to main content

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"].

HCL
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 Mistake

Driving count from a list and removing a middle item. Later indexes shift, so Terraform plans to recreate them. Use for_each, and use a moved block 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.

Found a mistake, an outdated step or a broken link?