hashicorp/terraform · error

cannot search an empty list

Error message

cannot search an empty list

What it means

Thrown by IndexFunc.Impl when the list argument is known but has length 0. There is nothing to search, so the function fails fast rather than returning a misleading result.

Source

Thrown at internal/lang/funcs/collection.go:201

		},
		{
			Name: "value",
			Type: cty.DynamicPseudoType,
		},
	},
	Type:         function.StaticReturnType(cty.Number),
	RefineResult: refineNotNull,
	Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
		if !(args[0].Type().IsListType() || args[0].Type().IsTupleType()) {
			return cty.NilVal, errors.New("argument must be a list or tuple")
		}

		if !args[0].IsKnown() {
			return cty.UnknownVal(cty.Number), nil
		}

		if args[0].LengthInt() == 0 { // Easy path
			return cty.NilVal, errors.New("cannot search an empty list")
		}

		for it := args[0].ElementIterator(); it.Next(); {
			i, v := it.Element()
			eq, err := stdlib.Equal(v, args[1])
			if err != nil {
				return cty.NilVal, err
			}
			if !eq.IsKnown() {
				return cty.UnknownVal(cty.Number), nil
			}
			if eq.True() {
				return i, nil
			}
		}
		return cty.NilVal, errors.New("item not found")

	},

View on GitHub (pinned to c9def3e214)

Solutions

  1. Guard the call: use a conditional or can() to skip when length is 0.
  2. Ensure the list is non-empty before invoking index().
  3. Provide a default element so the list always has content.

Example fix

# before
locals { i = index(var.items, "x") }   # var.items may be []
# after
locals {
  i = length(var.items) > 0 ? index(var.items, "x") : -1
}
Defensive patterns

Strategy: validation

Validate before calling

# only call index when the list is non-empty
locals {
  i = length(var.items) > 0 ? index(var.items, "x") : -1
}

Type guard

locals {
  non_empty = try(length(var.items) > 0, false)
  i         = local.non_empty ? index(var.items, "x") : -1
}

Try / catch

locals { i = try(index(var.items, "x"), -1) }

Prevention

When it happens

Trigger: index(local.empty_list, "x") where the list resolved to []; index(split(",", var.s), token) when var.s is empty so split returns a single empty element or [] in some paths.

Common situations: A list that is conditionally empty (filtered to nothing); an upstream for_each that produced no items; optional input omitted.

Related errors


AI-assisted analysis of hashicorp/terraform@c9def3e214 (2026-08-07). Data as JSON: /api/errors/84f16d117815877c. Report an issue: GitHub.