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.
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.
availability_zone = try(var.azs[2], var.azs[length(var.azs) - 1])
# for maps:
name = lookup(var.tags, "Name", "default")Validate input shapes
- Add a variable validation that the list has enough elements.
- Prefer for_each over count when iterating a map so keys are explicit.
- 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.