Skip to main content
The first Terraform meta-argument we’ll explore is 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 0 to count - 1.
  • Use count.index inside 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.
Example configuration using count:
With var.vm_count = 3, Terraform will create three VMs:
  • azurerm_virtual_machine.example[0]
  • azurerm_virtual_machine.example[1]
  • azurerm_virtual_machine.example[2]
Use 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.
When to avoid 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_each instead).
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.
Quick comparison: count vs for_each Practical tips
  • Combine count with locals and format()/join() to produce readable, unique names.
  • When switching from count to for_each, plan a migration strategy (state manipulation or resource replacement) to avoid accidental destruction.
  • Use terraform plan to review index changes before applying.
Further reading and references

Watch Video

Practice Lab