count meta-argument in Terraform lets you create multiple instances of the same resource from a single resource block. It uses a zero-based numeric index (count.index) that you can reference inside the resource to produce unique names, tags, or other per-instance values. This makes count ideal when you need several identical or nearly-identical resources, or when the number of instances should be driven by a variable.
Use
count when you want to scale identical resources by number. For stable identities or keyed collections, consider for_each instead (see the comparison below).
How count works
- Set
countto a number or a numeric variable (for example,var.vm_count). - Terraform creates that many instances and assigns each a numeric index starting at
0. - Inside the resource you can reference
count.indexto create unique values per instance. - To address an individual instance from another resource or an output, use an index on the resource address (for example:
aws_instance.example[1]).
count.index to generate unique names.
vm_count = 3, Terraform will create VMs named vm-0, vm-1, and vm-2.
Referencing instances
- Address the first instance:
azurerm_virtual_machine.example[0] - Get the name of the second instance:
azurerm_virtual_machine.example[1].name - Collect all names into an output:
Common uses and tips
- Use
count.indexinsidename,tags, or properties that accept strings to ensure uniqueness. - Combine
countwith other functions (for example,count = var.vm_count > 0 ? var.vm_count : 0) to handle conditional creation. - Avoid using
countwith resources that require stable identity across changes if individual items will be added/removed frequently — the numeric indexing can shift.
count vs for_each
| Feature | count | for_each |
|---|---|---|
| Indexing | Numeric, zero-based count.index | Keyed by element value or map keys |
| Stable identity | No — indices shift if items are inserted/removed | Yes — each key maps to a stable instance |
| Use-case | Create N identical instances, scale by a number | Create instances from a set/map where identity matters |
| Example | count = var.vm_count | for_each = toset(["a","b","c"]) |
When to prefer for_each
If you need stable, predictable identities for each instance (for example, when adding/removing single items),for_each is usually safer because it keys resources by a set or map value instead of a shifting numeric index.
Because
count is index-based, changing the number or ordering of instances can shift indices and cause Terraform to delete and recreate resources. If you need stable identities for resources, prefer for_each.