Terraform 19: The count meta-argument & count.index
easy⏱ 5 mincourseterraform
count makes N copies
Set count = <number> and Terraform creates that many instances of the block. Each instance is addressed by position — azurerm_subnet.app[0], [1], … — and count.index (0-based) is available inside to differentiate them, e.g. in a name.
variable "subnet_count" {
type = number
default = 3
}
resource "azurerm_subnet" "app" {
count = var.subnet_count
name = format("orders-app-subnet-%02d", count.index) # ...-00, -01, -02
resource_group_name = azurerm_resource_group.main.name
virtual_network_name = azurerm_virtual_network.main.name
address_prefixes = [cidrsubnet("10.0.0.0/16", 8, count.index)]
}
count = condition ? 1 : 0 toggles a resource
A very common idiom: gate a resource behind a boolean by giving it a count of 1 (create) or 0 (skip). The resource still exists as a list, so you reference the single instance as resource.name[0] — usually via one(...) or a try(...) when it may be absent.
variable "enable_prod_alerts" {
type = bool
default = false
}
# Created only when the flag is true — 1 copy, else 0
resource "azurerm_monitor_action_group" "oncall" {
count = var.enable_prod_alerts ? 1 : 0
name = "orders-oncall-ag"
resource_group_name = azurerm_resource_group.main.name
short_name = "oncall"
}
count is positional — reorder and it churns
Because instances are keyed by index, removing or reordering an item shifts every later index — Terraform will destroy and recreate resources that only "moved". Use count for a homogeneous number of things; when items have stable identities (a map/set of names), prefer for_each (next lesson).
Expand a count in TypeScript
Write expandCount(baseName, count) returning an array of count addresses like "orders-app-subnet[0]", "[1]", … using the index. Call it with "orders-app-subnet" and 3, and log JSON.stringify(result) (expect 3 entries ending in [0], [1], [2]).