count.
count lets Terraform create multiple instances from a single resource block by repeating that block a specified number of times. Each created instance receives a numeric index (starting at zero) which you can reference as count.index. This is ideal when you need several identical resources and only the quantity varies (for example, controlled by a variable).
Key behaviors
- Provide a literal number (e.g.,
count = 3) or a variable (e.g.,count = var.vm_count). - Terraform evaluates the resource block once for each index in the range
0tocount - 1. - Use
count.indexinside the resource to customize attributes per instance (for example, to create unique names).
count creates indexed resource instances and exposes the current index as count.index. Indexing begins at 0, so the first instance is count.index = 0.count:
var.vm_count = 3, Terraform will create three VMs:
azurerm_virtual_machine.example[0]azurerm_virtual_machine.example[1]azurerm_virtual_machine.example[2]
count.index to make attributes like name, computer_name, or tags unique without duplicating resource blocks.
When to use count
- You need a fixed number of otherwise-identical resources.
- Resources do not need stable non-numeric identities.
- Simpler, index-based generation is acceptable.
count
- Resources need stable identities across changes (e.g., unique keys or external references).
- You want to create resources based on a collection of keyed values (use
for_eachinstead).
Because
count assigns numeric indexes, changing the number or ordering of instances can shift indexes. Index shifting may cause Terraform to delete and recreate resources to restore a contiguous index sequence. If you require stable identities or want to map resources to keys, prefer for_each, which uses keys instead of numeric indexes and avoids index-shift problems.count vs for_each
Practical tips
- Combine
countwithlocalsandformat()/join()to produce readable, unique names. - When switching from
counttofor_each, plan a migration strategy (state manipulation or resource replacement) to avoid accidental destruction. - Use
terraform planto review index changes before applying.