Count vs for_each in Terraform: Key Differences and Usage
count creates multiple resource instances based on a number, while for_each creates instances based on items in a map or set. for_each offers more flexibility by allowing unique keys for each instance, making it easier to manage and reference resources individually.Quick Comparison
This table summarizes the main differences between count and for_each in Terraform.
| Aspect | count | for_each |
|---|---|---|
| Type of input | A single number (integer) | A map or set of strings |
| Instance identification | By index number (0, 1, 2...) | By unique keys from the collection |
| Use case | Simple repeated resources | Resources needing unique keys or complex data |
| Referencing instances | Using index (e.g., resource[0]) | Using keys (e.g., resource["key1"] ) |
| Supports complex keys | No | Yes |
| Error handling on missing keys | Less flexible | More explicit and safer |
Key Differences
count is best when you want to create a fixed number of identical resources. It uses a simple integer to decide how many copies to make. Each resource instance is identified by a numeric index starting at zero. This makes it easy for simple repetition but harder to manage when resources need unique identifiers.
for_each works with collections like maps or sets, allowing each resource instance to have a unique key. This makes it easier to track and update specific resources individually. For example, if you have a map of server names to IPs, for_each lets you create one resource per server with its name as the key.
Using for_each improves clarity and reduces errors when resources need to be added or removed dynamically because Terraform can detect changes by keys rather than just counts. However, for_each requires the input to be a collection with unique keys, while count only needs a number.
Code Comparison
Here is an example creating three AWS S3 buckets using count. Each bucket gets a numbered suffix.
resource "aws_s3_bucket" "example" { count = 3 bucket = "my-bucket-${count.index}" acl = "private" }
for_each Equivalent
The same three buckets created using for_each with a set of unique names.
resource "aws_s3_bucket" "example" { for_each = toset(["bucket-a", "bucket-b", "bucket-c"]) bucket = each.key acl = "private" }
When to Use Which
Choose count when you need to create a simple number of identical resources without unique identifiers. It is straightforward and works well for fixed-size sets.
Choose for_each when your resources need unique keys or when you want to manage resources dynamically by name or other identifiers. It offers better clarity and safer updates when resources change.
Key Takeaways
count creates resources by number; for_each creates by unique keys.for_each is better for managing resources with unique names or identifiers.count for simple repeated resources without unique keys.for_each improves clarity and reduces errors in dynamic resource sets.count and by key with for_each.