TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › for_each & Stable Keys

for_each & Stable Keys

for_each creates one instance per element of a map or a set of strings. Each instance is addressed by its key, local_file.team["billing"], so adding or removing one element touches exactly one instance, whatever its position. Inside the block, each.key and each.value are the current element.

The count trap, fixed

The same example as in the count lesson, keyed by team name:

bash · try it yourself
mkdir fe && cd fe
cat > main.tf <<'HCL'
variable "teams" {
  type    = set(string)
  default = ["api", "billing", "search"]
}

resource "local_file" "team" {
  for_each = var.teams
  filename = "team-${each.key}.txt"
  content  = "${each.key}\n"
}
HCL
tofu init >/dev/null
tofu apply -auto-approve >/dev/null
tofu state list
echo "--- remove \"billing\""
tofu plan -var 'teams=["api", "search"]' | grep -E '^  #|^Plan:'
local_file.team["api"]
local_file.team["billing"]
local_file.team["search"]
--- remove "billing"
  # local_file.team["billing"] will be destroyed
  # (because key ["billing"] is not in for_each map)
Plan: 0 to add, 0 to change, 1 to destroy.

One destroy, nothing else. That is why most real-world modules use for_each for anything built from a collection.

Maps carry settings per instance

With a map, each.value holds that element's settings. Objects in a map are a clean way to describe several similar resources that differ in a few fields:

bash · try it yourself
mkdir m && cd m
cat > main.tf <<'HCL'
variable "queues" {
  type = map(object({
    retention_days = number
    fifo           = optional(bool, false)
  }))
  default = {
    orders = { retention_days = 4, fifo = true }
    emails = { retention_days = 1 }
  }
}

resource "local_file" "queue" {
  for_each = var.queues
  filename = "queues/${each.key}${each.value.fifo ? ".fifo" : ""}.conf"
  content  = "retention_days=${each.value.retention_days}\n"
}

output "queue_files" {
  value = { for name, f in local_file.queue : name => f.filename }
}
HCL
tofu init >/dev/null
tofu apply -auto-approve | sed -n '/^Outputs:/,$p'
Outputs:

queue_files = {
  "emails" = "queues/emails.conf"
  "orders" = "queues/orders.fifo.conf"
}

A resource with for_each is itself a map of instances, so { for k, v in local_file.queue : … } and values(local_file.queue)[*].id work on it.

Keys must be known at plan time

The keys decide which instances exist, so they must be known before anything is created. Values may be unknown, keys may not:

bash · try it yourself
mkdir k && cd k
cat > main.tf <<'HCL'
resource "terraform_data" "bucket" {
  count = 2
  input = "bucket-${count.index}"
}

resource "terraform_data" "policy" {
  for_each = toset(terraform_data.bucket[*].id)   # ids only exist after apply
  input    = each.key
}
HCL
tofu init >/dev/null
tofu plan >/dev/null; echo "exit=$?"

Error: Invalid for_each argument

  on main.tf line 7, in resource "terraform_data" "policy":
   7:   for_each = toset(terraform_data.bucket[*].id)   # ids only exist after apply
    ├────────────────
    │ terraform_data.bucket is tuple with 2 elements

The "for_each" set includes values derived from resource attributes that
cannot be determined until apply, and so OpenTofu cannot determine the full
set of keys that will identify the instances of this resource.

When working with unknown values in for_each, it's better to use a map value
where the keys are defined statically in your configuration and where only
the values contain apply-time results.

Alternatively, you could use the planning option
-exclude=terraform_data.policy to first apply without this object, and then
apply normally to converge.
exit=1

OpenTofu's message suggests a two-step apply with -exclude; Terraform's suggests -target. Both are workarounds. Build keys from things you write in the code (names, variables), never from ids the API generates; pass the id as the value instead (for_each = { for i, b in terraform_data.bucket : "bucket-${i}" => b.id }).

Converting lists

for_each refuses a plain list (its order would be ambiguous as an identity). Convert:

You have Write
a list of unique strings for_each = toset(var.names)
a list of objects with a name field for_each = { for o in var.items : o.name => o }
a nested structure (users × groups) flatten it into a map with composite keys: "${u}-${g}" => { … }

for_each also works on module blocks (one module instance per environment or per region), and on dynamic nested blocks, next lesson.

Test yourself

How is an instance of aws_iam_user.this created with for_each = toset(["ada", "grace"]) addressed?

  1. aws_iam_user.this[0]
  2. aws_iam_user.this["ada"]
  3. aws_iam_user.this.ada
  4. aws_iam_user.ada

Why does for_each = toset(aws_instance.web[*].id) fail on the first plan?

  1. Sets are not allowed
  2. Instance ids are unknown until apply, and for_each keys must be known at plan time
  3. for_each can't reference other resources
  4. ids contain dashes

Which expression turns a list of objects with a name field into a valid for_each value?

  1. var.items
  2. toset(var.items)
  3. { for o in var.items : o.name => o }
  4. var.items[*].name