hashicorp/terraform · error

index %s out of range in %#v

Error message

index %s out of range in %#v

What it means

Returned by pathFromFlatmapKeyTuple (paths.go:177) when an index parsed from a flatmap key segment is greater than or equal to the number of element types in the tuple schema (idx >= len(etys)). Tuples are fixed-length and positionally typed, so an index beyond the declared arity has no corresponding element type.

Source

Thrown at internal/configs/hcl2shim/paths.go:177

	var path cty.Path
	var err error

	k, rest := pathSplit(key)

	// we don't need to convert the index keys to paths
	if k == "#" {
		return path, nil
	}

	idx, err := strconv.Atoi(k)
	if err != nil {
		return path, err
	}

	path = cty.Path{cty.IndexStep{Key: cty.NumberIntVal(int64(idx))}}

	if idx >= len(etys) {
		return path, fmt.Errorf("index %s out of range in %#v", key, etys)
	}

	if rest == "" {
		return path, nil
	}

	ty := etys[idx]

	p, err := pathFromFlatmapKeyValue(rest, ty.ElementType())
	if err != nil {
		return path, err
	}

	return append(path, p...), nil
}

func pathFromFlatmapKeyMap(key string, ty cty.Type) (cty.Path, error) {
	var path cty.Path

View on GitHub (pinned to c9def3e214)

Solutions

  1. Compare the index in the message against the tuple's declared arity; remove the out-of-range element key or extend the schema.
  2. If you intentionally shrank the tuple, write a state migration to drop the extra indexed entries and update the count.
  3. Pin the provider version matching the state, or re-import to regenerate a consistent flatmap.
  4. Audit the diff source to ensure it does not emit indices beyond the schema arity.

Example fix

// before — schema: cty.Tuple([string, number])  (arity 2)
// state key: "config.2.value"  (index 2 out of range)

// after — keep indices within arity
"config.0": "web"
"config.1": "8080"
Defensive patterns

Strategy: validation

Validate before calling

// Ensure a tuple index is within the schema arity before navigation
func indexInRange(idx int, etys []cty.Type) bool {
    return idx >= 0 && idx < len(etys)
}

Type guard

func indexInRange(idx int, etys []cty.Type) bool {
    return idx >= 0 && idx < len(etys)
}

Prevention

When it happens

Trigger: Navigating a flatmap key like 'config.5.value' when the tuple schema only declares, say, 3 element types. The strconv.Atoi succeeds but the bounds check `idx >= len(etys)` fails.

Common situations: The tuple schema's arity was reduced (elements removed) while state still references higher indices. State written by a provider version with a larger tuple. Manually edited state introducing out-of-range index keys.

Related errors


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