Terraform 17: for_each over a map with data + key vault secrets
easy⏱ 5 mincourseterraform
for_each over a map of services
Set for_each = local.services and Terraform creates one instance per map entry. Inside the block, each.key is the map key and each.value is that entry's object. Each instance is addressed as <resource>["<key>"] — stable keys mean adding a service doesn't disturb the others.
locals {
environment = "dev"
services = {
orders = { secret_name = "orders-conn" }
billing = { secret_name = "billing-conn" }
notifications = { secret_name = "notifications-conn" }
}
}
Wiring data + for_each + secret together
Look up the shared vault once with a data source, then for_each a key_vault_secret resource over the services map, writing each service's connection string into that vault. One data lookup feeds every generated secret.
data "azurerm_key_vault" "shared" {
name = "orders-kv-${local.environment}"
resource_group_name = "myorg-platform-${local.environment}-rg"
}
resource "azurerm_key_vault_secret" "conn" {
for_each = local.services
name = each.value.secret_name
value = var.connection_strings[each.key] # supplied via TF_VAR_*, never hard-coded
key_vault_id = data.azurerm_key_vault.shared.id
}
# Instances created:
# azurerm_key_vault_secret.conn["orders"]
# azurerm_key_vault_secret.conn["billing"]
# azurerm_key_vault_secret.conn["notifications"]
for_each vs count for stable addresses
Prefer for_each over count for collections of named things. count indexes by position ([0], [1]), so removing the middle item reshuffles everything after it and Terraform destroys/recreates resources. for_each keys by name, so each instance is stable.
Compute the for_each instance addresses
Given services (a map key -> config), write secretAddresses(services) returning the sorted array of Terraform addresses azurerm_key_vault_secret.conn["<key>"], one per map key, sorted alphabetically by key. Log JSON.stringify(secretAddresses(services)). For keys billing, notifications, orders you should get those three addresses in alphabetical order.