hashicorp/terraform · error

cannot search an empty list

Error message

cannot search an empty list

What it means

Thrown by `index()` (IndexFunc) when the first argument is a known list/tuple of length zero. Searching an empty sequence can never match, so the function fails fast with this explicit message instead of falling through to the 'item not found' path. Unknown lists return unknown and do not trigger this.

Solutions

  1. Guard with a length check: `length(var.list) > 0 ? index(var.list, val) : -1`.
  2. Ensure the source list is actually populated before calling index().
  3. Reconsider the workflow: if the list may legitimately be empty, handle that case explicitly rather than relying on index().

Example fix

// before
locals { i = index(var.items, target) }   # var.items may be []

// after
locals { i = length(var.items) > 0 ? index(var.items, target) : -1 }
Defensive patterns

Strategy: validation

Validate before calling

# HCL: guard the empty case
locals { i = length(var.list) > 0 ? index(var.list, val) : -1 }

Type guard

# HCL membership pre-check
locals { i = contains(var.list, val) ? index(var.list, val) : -1 }

Prevention

When it happens

Trigger: Calling `index(var.list, val)` where var.list evaluates to `[]`. A dynamic list that happens to be empty at apply time.

Common situations: A list populated from a filtered comprehension that filtered everything out. An empty `for_each`-derived list passed to index(). A conditional returning [] in the active workspace.

Related errors


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

Appendix: 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 d32a084675)