Skip to content
Latchkey

Terraform "Invalid for_each argument" in CI

A for_each was given a value Terraform cannot use to build instances: it is null, it is not a map or set of strings, or its keys depend on values that are only known after apply.

What this error means

plan fails with "Invalid for_each argument", either because the collection is the wrong type/null, or because the keys depend on a computed attribute that is unknown until apply. It is deterministic for type errors.

terraform output
Error: Invalid for_each argument

  on main.tf line 8, in resource "aws_subnet" "this":
   8:   for_each = toset([for s in aws_instance.web : s.id])

The "for_each" map includes keys derived from resource attributes that cannot be
determined until apply, and so Terraform cannot determine the full set of keys.

Common causes

Keys not known until apply

When for_each keys come from another resource’s computed attribute (an id/ARN created during apply), Terraform cannot build the instance set at plan time.

Wrong type or null collection

for_each requires a map or a set of strings. A list, a null value, or a set with unknown elements is rejected.

How to fix it

Use stable, plan-time-known keys

Key for_each on static identifiers (names from variables/locals), not on attributes computed during apply.

main.tf
resource "aws_subnet" "this" {
  for_each = var.subnets   # map of known keys -> config
  cidr_block = each.value.cidr
}

Coerce the value to a valid type

Make sure the argument is a map or toset(list_of_strings), and never null.

main.tf
for_each = toset(var.names)   # set of strings
# or guard null:
for_each = var.enabled ? var.config : {}

How to prevent it

  • Key for_each on input-derived values known at plan time, not computed attributes.
  • Ensure the value is a map or set of strings, never a list or null.
  • Use toset() and null-guards (? : {}) to keep the type valid.

Frequently asked questions

What causes ""Invalid for_each argument""?
When for_each keys come from another resource’s computed attribute (an id/ARN created during apply), Terraform cannot build the instance set at plan time.
How do I fix "Invalid for_each argument"?
Key for_each on static identifiers (names from variables/locals), not on attributes computed during apply.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card