Terraform "Invalid function argument" / "Invalid index" in CI
A function or index expression got a value it cannot use - a null where a string was required, a wrong type, or a key/index that does not exist. Terraform stops because the expression cannot evaluate.
What this error means
A plan fails with "Invalid function argument", "Call to function ... failed", or "Invalid index", pointing at the expression. It usually appears when a variable is null/empty or a lookup key is missing.
Error: Invalid index
on main.tf line 8, in locals:
8: name = var.names["web"]
The given key does not identify an element in this collection value.Common causes
Null or wrong-typed input to a function
Passing a null or unexpected type (e.g. a list where a string is expected) to a function like length, lookup, or cidrsubnet makes the call fail.
Indexing a missing key or out-of-range element
Accessing map["key"] for a key that does not exist, or list[3] beyond the end, raises "Invalid index".
How to fix it
Guard against null and missing keys
Use try, lookup with a default, or coalesce so missing values do not crash evaluation.
locals {
name = lookup(var.names, "web", "default-web")
port = try(var.config.port, 8080)
}Validate inputs and types
- Add
validationblocks or explicit types to variables so bad input fails clearly. - Confirm the value is the type the function expects (string vs list vs number).
- For optional object attributes, use
optional(...)with defaults so they are never null unexpectedly.
How to prevent it
- Type your variables and add
validationblocks. - Use
try/lookup/coalesceto handle optional or missing values. - Run
terraform validatein CI to catch many of these before apply.