How to fix Error: Invalid index - out of range in Terraform

TerraformINTERMEDIATEMEDIUMUpdated Dec 31, 2025ยท 145 views

This error occurs when Terraform tries to access a list or map element using an index that doesn't exist. Common causes include accessing empty lists, using count with mismatched list sizes, or using incorrect index calculations.

Quick fix

Fixes Error: Invalid index - out of range

terraform console
> var.my_list
> length(var.my_list)
  1. Verify your list size matches your access pattern
  2. Use length() check for conditional access
  3. Replace bracket notation with try() function
  4. Use element() instead of direct bracket notation
terraform โ€” error
terraform console
> var.my_list
> length(var.my_list)
Error: Invalid index - out of range

What this error means

The 'Invalid index - out of range' error happens when your Terraform configuration attempts to access an element in a list, tuple, or map using an index number that exceeds the bounds of that collection. This is a validation error that Terraform catches during the planning phase. For example, trying to access element [2] in a list that only has 2 elements (indices 0 and 1) will trigger this error. This commonly occurs when using dynamic count or for_each iterations, data source queries that return unexpected numbers of results, or splat expressions combined with direct indexing.

Typical symptoms

  • Terraform plan fails with 'Invalid index - out of range' message
  • Error occurs after modifying count values or adding/removing list elements
  • Index 1 out of range for list variable (max 1) error message
  • Splat expression with square bracket indexing fails during plan
  • Accessing first element of data source returns index out of range
  • Configuration works with small datasets but fails with larger ones

Common causes

  1. Accessing a list element with count.index when the list has fewer elements than the count value
  2. Data source returning fewer results than expected but code assumes specific index exists
  3. Using direct bracket notation with a hardcoded index larger than list length
  4. Removing items from the beginning or middle of a list while using count instead of for_each
  5. Splat expression generating fewer results than anticipated and being indexed directly
  6. Incrementing count value without verifying corresponding list/data source has grown accordingly

How to fix "Error: Invalid index - out of range"

1Verify your list size matches your access pattern

Check that any list you're indexing actually has the number of elements you expect. Use Terraform console to inspect the actual data:

hcl
terraform console
> var.my_list
> length(var.my_list)

If the list is empty or smaller than expected, this is your root cause.

2Use length() check for conditional access

Wrap direct index access with a length check to safely access elements only if they exist:

hcl
value = length(var.my_list) > 0 ? var.my_list[0] : null

This ensures you only attempt to access indices that exist in the collection.

3Replace bracket notation with try() function

Use the try() function (available in Terraform 0.13+) to gracefully handle out-of-range access:

hcl
value = try(var.my_list[2], "default_value")

If the index doesn't exist, try() returns the second argument (fallback value) instead of erroring.

4Use element() instead of direct bracket notation

The element() function provides safer list access and can wrap around if needed:

hcl
# Instead of:
value = var.my_list[count.index]

# Use:
value = element(var.my_list, count.index)

This is particularly useful when working with count-based iteration.

5Switch from count to for_each for dynamic resources

If you're managing multiple resources, use for_each instead of count to avoid index-based problems:

hcl
resource "aws_instance" "example" {
  for_each = var.instances  # Use map keys instead of indices
  
  ami           = each.value.ami
  instance_type = each.value.type
}

for_each uses keys rather than numeric indices, preventing issues when adding/removing items.

6Validate data source results before indexing

When accessing data source results, always verify the query returned data:

hcl
data "aws_instances" "example" {
  filter {
    name   = "tag:Name"
    values = ["MyInstance"]
  }
}

resource "aws_security_group_rule" "example" {
  # Safe access - only if data source returned results
  instance_id = length(data.aws_instances.example.ids) > 0 ? data.aws_instances.example.ids[0] : null
}

This prevents errors when queries unexpectedly return no results.

Advanced notes

When using splat expressions combined with direct indexing like resource.*.id[count.index], consider using the one() function (Terraform 1.0+) for single results or dropping the bracket entirely: resource.*.id returns all IDs directly. If you absolutely need bracket notation, use element(resource.*.id, count.index) instead. Be particularly careful when modifying count values mid-project - Terraform may destroy and recreate resources if you change from one index to another. Use state management commands like terraform state rm and terraform import if you encounter persistent state conflicts.

Frequently asked questions

What does "Error: Invalid index - out of range" mean?
The 'Invalid index - out of range' error happens when your Terraform configuration attempts to access an element in a list, tuple, or map using an index number that exceeds the bounds of that collection. This is a validation error that Terraform catches during the planning phase. For example, trying to access element [2] in a list that only has 2 elements (indices 0 and 1) will trigger this error.
How do I fix "Error: Invalid index - out of range"?
This error occurs when Terraform tries to access a list or map element using an index that doesn't exist. Common causes include accessing empty lists, using count with mismatched list sizes, or using incorrect index calculations.
What causes "Error: Invalid index - out of range"?
Accessing a list element with count.index when the list has fewer elements than the count value Data source returning fewer results than expected but code assumes specific index exists Using direct bracket notation with a hardcoded index larger than list length
Is the "Error: Invalid index - out of range" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading