Terraform 36: Terraform Modules 4: Deploying many with for_each
easy⏱ 5 mincourseterraform
for_each over a map of configs
Give for_each a map keyed by a stable identifier. Inside the block, each.key is the map key and each.value is that entry's object. One block, many instances — add a service to the map and the next apply creates it.
locals {
services = {
orders = { sku = "P1v3" }
billing = { sku = "P1v3" }
notifications = { sku = "B1" }
}
}
module "app" {
source = "./modules/function-app"
for_each = local.services
app_name = each.key
service_plan_sku = each.value.sku
environment_name = "dev"
}
Instance address is module.<name>["<key>"]
With for_each, module.app becomes a map of instances. Reference one as module.app["orders"].function_id. The map key — not a numeric index — is the stable identity, so removing notifications never disturbs orders in the state file.
Prefer for_each over count for named things
count indexes by position (module.app[0]), so deleting the middle item renumbers and recreates everything after it. For named resources, for_each over a map keeps identities stable. Reach for count only for truly interchangeable copies.
Compute the instance addresses
Given the service names of a for_each map, write moduleInstanceAddresses(names) returning module.app["<name>"] for each. Log JSON.stringify(moduleInstanceAddresses(["orders", "billing", "notifications"])) — the first entry must be module.app["orders"].