Skip to content
Latchkey

Terraform "Invalid index" (list/map) in CI

An expression indexes a list at a position that does not exist, or a map by a key it does not contain, so the lookup has no value to return.

What this error means

plan fails with "Invalid index", pointing at a [n] or ["key"] access. It surfaces when a list is empty/shorter than expected, or a map lookup uses a key that is not present.

terraform
Error: Invalid index

  on main.tf line 14, in resource "aws_subnet" "this":
  14:   availability_zone = var.azs[2]

The given key does not identify an element in this collection value: the given
index is greater than or equal to the length of the collection.

Common causes

List index out of range

Indexing var.azs[2] when the list has fewer than three elements has no element to return.

Map key missing

Looking up map["key"] where the key is absent fails; this is common with data that varies by environment.

How to fix it

Guard the access with length/lookup defaults

Use try() or lookup() with a default, or validate the collection length first.

main.tf
availability_zone = try(var.azs[2], var.azs[length(var.azs) - 1])
# for maps:
name = lookup(var.tags, "Name", "default")

Validate input shapes

  1. Add a variable validation that the list has enough elements.
  2. Prefer for_each over count when iterating a map so keys are explicit.
  3. Confirm environment-specific maps contain every key the config reads.

How to prevent it

  • Guard list/map access with try() or lookup() defaults.
  • Validate collection lengths and required keys in variable blocks.
  • Prefer for_each over positional indexing where possible.

Frequently asked questions

What causes ""Invalid index""?
Indexing var.azs[2] when the list has fewer than three elements has no element to return.
How do I fix "Invalid index"?
Use try() or lookup() with a default, or validate the collection length first.

Related guides

References

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