count and for_each meta-arguments in OpenTofu. Both approaches let you duplicate a single resource block, but differ in indexing and lifecycle behavior.
| Meta-Argument | Key Characteristic | Best Use Case |
|---|---|---|
| count | Integer-based, zero-indexed | Create a fixed number of identical resources |
| for_each | Key-based, uses a set or map of values | Stable addressing of dynamic or named items |
1. Using count
The count meta-argument accepts an integer and creates that many instances of a resource.
Dynamic count with length()
Instead of hardcoding an integer, drive count from a list:
count.index:
count.index = 0→Name = "web1"count.index = 1→Name = "web2"count.index = 2→Name = "web3"
Removing or reordering items in the
webservers list causes all subsequent resources to be reindexed. This can lead to unintended in-place updates instead of only removing the orphaned resource."web1":
2. Using for_each
The for_each meta-argument uses a set or map, giving each resource a stable key based on its value.
"web1" from the set and run tofu plan, only that resource is destroyed: