Terraform

How to use a module with for_each to create networks per availability zone?

Difficulty: unrated

Source: bregman-arie/devops-exercises by Arie Bregman

Answer

module "subnet" {
  source   = "../modules/subnet"
  for_each = toset(var.azs)

  name = "subnet-${each.key}"
  az   = each.value
}

for_each keeps addresses stable and lets you add or remove AZs without re-creating the entire module.