Terraform has four iteration tools, and each solves a different problem:
| Tool | Produces | Use it to |
|---|---|---|
for expression |
A value (list/tuple or map/object) | Transform, filter or reshape data |
count |
N instances of a resource or module, indexed [0], [1]… |
Create identical copies, or toggle 0/1 |
for_each |
One instance per map key or set element, indexed ["key"] |
Create a resource per item in a collection |
dynamic block |
Repeated nested blocks inside a resource | Generate ingress {}, ip_restriction {}, etc. |
A typical module uses all four together: a for expression reshapes an input variable into a map, for_each creates resources from that map, dynamic fills in nested blocks per resource, and another for expression builds the output.
for expressions¶
Syntax¶
[for <ITEM> in <COLLECTION> : <VALUE_EXPR>] # → tuple (list-like)
[for <ITEM> in <COLLECTION> : <VALUE_EXPR> if <COND>] # with filter
{for <ITEM> in <COLLECTION> : <KEY_EXPR> => <VALUE_EXPR>} # → object (map-like)
{for <ITEM> in <COLLECTION> : <KEY_EXPR> => <VALUE_EXPR>...} # group duplicate keys
The outer brackets decide the result type: [ ] gives a list, { } gives a map. The input can be any collection.
Iteration variables¶
| Input type | One variable | Two variables |
|---|---|---|
| list / tuple | for v in list → the element |
for i, v in list → index, element |
| set | for v in set → the element |
for v, v2 in set → both are the element (sets have no keys) |
| map / object | for v in map → the value |
for k, v in map → key, value |
Lists¶
locals {
names = ["web", "api", "worker"]
upper = [for n in local.names : upper(n)] # ["WEB", "API", "WORKER"]
indexed = [for i, n in local.names : "${i}-${n}"] # ["0-web", "1-api", "2-worker"]
no_web = [for n in local.names : n if n != "web"] # ["api", "worker"]
}
Maps¶
locals {
vm_sizes = {
web = "Standard_B2s"
api = "Standard_D2s_v5"
worker = "Standard_D4s_v5"
}
# map → list
size_list = [for name, size in local.vm_sizes : "${name}=${size}"]
# map → map (transform values)
vm_names = { for name, size in local.vm_sizes : name => "vm-${name}-${var.env}" }
# map → map (filter)
big_vms = { for name, size in local.vm_sizes : name => size if can(regex("D4", size)) }
# invert a map
by_size = { for name, size in local.vm_sizes : size => name... } # see grouping below
}
List of objects → map keyed by an attribute¶
This is the most important for pattern in Terraform, because for_each needs a map with stable keys:
variable "subnets" {
type = list(object({
name = string
address_prefix = string
}))
}
locals {
subnets_by_name = { for s in var.subnets : s.name => s }
# {
# "aks" = { name = "aks", address_prefix = "10.10.0.0/22" }
# "data" = { name = "data", address_prefix = "10.10.4.0/24" }
# }
}
If two elements share a key, Terraform errors with "Duplicate object key". That's usually what you want: it catches a duplicated subnet name at plan time.
Grouping with ...¶
The ellipsis after the value collects all values with the same key into a list:
locals {
apps = [
{ name = "billing", team = "payments" },
{ name = "ledger", team = "payments" },
{ name = "portal", team = "web" },
]
apps_by_team = { for a in local.apps : a.team => a.name... }
# { payments = ["billing", "ledger"], web = ["portal"] }
}
Result ordering¶
forover a map iterates keys in lexical order.forover a set of strings iterates in lexical order; sets of other types have an undefined but consistent order.- A
{ }result is a map, so its keys come out sorted no matter how you built it.
Walkthrough: a map output from a for_each resource¶
From an earlier note. A networking module creates subnets with for_each:
resource "azurerm_subnet" "this" {
for_each = { for s in var.subnets : s.name => s }
name = each.value.name
resource_group_name = var.resource_group_name
virtual_network_name = azurerm_virtual_network.this.name
address_prefixes = [each.value.address_prefix]
}
output "subnet_ids" {
value = { for k, s in azurerm_subnet.this : k => s.id }
}
What the output does. Because the resource uses for_each, azurerm_subnet.this isn't one object. It's a map of instances keyed by subnet name:
azurerm_subnet.this["aks"]
azurerm_subnet.this["data"]
azurerm_subnet.this["web"]
The for expression walks that map:
kis each key (the subnet name, from thefor_eachmap)sis the whole subnet resource object for that keyk => s.idbuilds one map entry: name → ID
Result:
subnet_ids = {
"aks" = "/subscriptions/.../virtualNetworks/vnet-dev/subnets/aks"
"data" = "/subscriptions/.../virtualNetworks/vnet-dev/subnets/data"
"web" = "/subscriptions/.../virtualNetworks/vnet-dev/subnets/web"
}
Why it's written that way. Callers can pick subnets by name, which survives adding, removing and reordering subnets:
module "aks" {
source = "../modules/aks"
subnet_id = module.network.subnet_ids["aks"]
}
A list output ([for s in azurerm_subnet.this : s.id]) would force callers to use positions like [0], and positions change when the input changes.
count¶
resource "azurerm_public_ip" "lb" {
count = var.public_ip_count
name = "pip-lb-${var.env}-${count.index + 1}"
location = var.location
resource_group_name = var.resource_group_name
allocation_method = "Static"
sku = "Standard"
}
# Reference: azurerm_public_ip.lb[0], azurerm_public_ip.lb[*].ip_address
count accepts a whole number known at plan time. Inside the block, count.index is the instance's position.
Use count for:
- Toggling a resource on or off:
count = var.enabled ? 1 : 0(conditionals) - Truly identical, interchangeable copies where position doesn't matter
for_each¶
resource "azurerm_resource_group" "this" {
for_each = {
app = "canadacentral"
data = "canadacentral"
dr = "canadaeast"
}
name = "rg-${each.key}-${var.env}"
location = each.value
}
# Reference: azurerm_resource_group.this["app"]
for_each accepts a map or a set of strings. Inside the block:
each.key: the map key, or the set elementeach.value: the map value, or (for sets) the same aseach.key
count vs for_each¶
The classic failure with count over a list:
variable "users" { default = ["alice", "bob", "carol"] }
resource "azuread_user" "u" {
count = length(var.users)
user_principal_name = "${var.users[count.index]}@example.com"
# ...
}
Remove "bob" and every user after him shifts down one index. Terraform sees [1] change from bob to carol and [2] disappear, so it modifies or recreates carol and destroys [2], rather than just deleting bob. With for_each = toset(var.users) the addresses are ["alice"], ["bob"], ["carol"], and removing bob deletes exactly bob.
Rule: use for_each for anything that comes from a collection. Use count only for 0/1 toggles and genuinely interchangeable copies.
Migrating from count to for_each changes addresses. Use moved blocks, one per instance:
moved {
from = azuread_user.u[0]
to = azuread_user.u["alice"]
}
Keys must be known at plan time¶
# ❌ IDs don't exist until apply
for_each = toset(azurerm_subnet.this[*].id)
# ✅ key by something from configuration, put the unknown in the value
for_each = { for name, s in azurerm_subnet.this : name => s.id }
Map values can be unknown; only the keys must be known. Build keys from input data (names), never from IDs or other computed attributes.
Sets of objects don't work directly¶
for_each = toset(var.list_of_objects) errors because for_each needs string keys. Convert to a map with a for expression keyed by a unique attribute (see above).
Chaining for_each resources¶
When one resource is created per element of another, iterate over the first resource directly. The keys line up and dependencies are implicit:
resource "azurerm_network_security_group" "this" {
for_each = azurerm_subnet.this
name = "nsg-${each.key}"
location = var.location
resource_group_name = var.resource_group_name
}
resource "azurerm_subnet_network_security_group_association" "this" {
for_each = azurerm_subnet.this
subnet_id = each.value.id
network_security_group_id = azurerm_network_security_group.this[each.key].id
}
Nested data: flatten and setproduct¶
for_each creates one level of instances. For "one thing per (A, B) pair", flatten the pairs into a single map first.
Parent/child: flatten¶
variable "vnets" {
type = map(object({
address_space = list(string)
subnets = map(string) # subnet name → prefix
}))
}
locals {
subnet_list = flatten([
for vnet_name, vnet in var.vnets : [
for subnet_name, prefix in vnet.subnets : {
key = "${vnet_name}.${subnet_name}"
vnet_name = vnet_name
subnet_name = subnet_name
prefix = prefix
}
]
])
subnets = { for s in local.subnet_list : s.key => s }
}
resource "azurerm_subnet" "this" {
for_each = local.subnets
name = each.value.subnet_name
virtual_network_name = azurerm_virtual_network.this[each.value.vnet_name].name
resource_group_name = var.resource_group_name
address_prefixes = [each.value.prefix]
}
The composite key "hub.aks" keeps addresses readable: azurerm_subnet.this["hub.aks"].
Every combination: setproduct¶
locals {
environments = ["dev", "test", "prod"]
regions = ["canadacentral", "canadaeast"]
env_regions = {
for pair in setproduct(local.environments, local.regions) :
"${pair[0]}-${pair[1]}" => { env = pair[0], region = pair[1] }
}
# { "dev-canadacentral" = {...}, "dev-canadaeast" = {...}, ... }
}
dynamic blocks¶
Arguments can be built with expressions, but nested blocks can't. dynamic generates them:
variable "ip_restrictions" {
type = list(object({
name = string
ip_address = string
priority = number
}))
default = []
}
resource "azurerm_linux_web_app" "this" {
# ...
site_config {
dynamic "ip_restriction" {
for_each = var.ip_restrictions
content {
name = ip_restriction.value.name
ip_address = ip_restriction.value.ip_address
priority = ip_restriction.value.priority
action = "Allow"
}
}
}
}
- The label (
"ip_restriction") is the nested block type to generate. - The iterator is named after the label by default (
ip_restriction.key,ip_restriction.value). Rename it withiterator = rulewhen nesting dynamic blocks or when the name is long. for_eachtakes any collection; for lists,.keyis the index.
Optional nested block with splat¶
dynamic "identity" {
for_each = var.identity[*] # null → no block; object → one block
content {
type = identity.value.type
identity_ids = identity.value.identity_ids
}
}
Nested dynamic blocks¶
dynamic "rule" {
for_each = var.rules
iterator = r
content {
name = r.value.name
dynamic "match_condition" {
for_each = r.value.conditions
iterator = c
content {
variable = c.value.variable
operator = c.value.operator
values = c.value.values
}
}
}
}
Don't overuse dynamic¶
dynamic makes configuration harder to read. If a block appears a fixed number of times, write it out. Use dynamic when the count genuinely varies per caller. And remember the argument form exists for some providers' attributes. If the provider schema says something is an argument holding a list of objects, assign it directly.
Iterating modules¶
Modules take count and for_each exactly like resources:
module "app" {
source = "../modules/web-app"
for_each = var.apps # map(object({...}))
name = each.key
sku = each.value.sku
settings = each.value.app_settings
}
output "app_hostnames" {
value = { for name, m in module.app : name => m.default_hostname }
}
A module with a provider block inside it can't be used with count or for_each. That's one reason child modules should never configure providers (modules). OpenTofu 1.9+ also allows for_each on provider blocks themselves, which Terraform doesn't (OpenTofu).
Debugging loops¶
$ terraform console
> { for s in var.subnets : s.name => s.address_prefix }
> flatten([for k, v in var.vnets : [for s, p in v.subnets : "${k}.${s}"]])
> keys(azurerm_subnet.this)
Paste the expression into terraform console before putting it in a resource. On Terraform 1.16, terraform console -scope=module.network evaluates inside a child module.
Related¶
- Conditionals: the 0/1 iteration tricks
- Functions:
flatten,setproduct,merge,zipmap,one - State refactoring:
movedblocks when switching iteration styles