Skip to content
Latchkey

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.

terraform output
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.

main.tf
locals {
  name = lookup(var.names, "web", "default-web")
  port = try(var.config.port, 8080)
}

Validate inputs and types

  1. Add validation blocks or explicit types to variables so bad input fails clearly.
  2. Confirm the value is the type the function expects (string vs list vs number).
  3. For optional object attributes, use optional(...) with defaults so they are never null unexpectedly.

How to prevent it

  • Type your variables and add validation blocks.
  • Use try/lookup/coalesce to handle optional or missing values.
  • Run terraform validate in CI to catch many of these before apply.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →