Skip to content

Function element()

📝 Description

The element function retrieves a single element from a list. If the index is greater than the number of elements in the list, the index is "wrapped around" using a modulo operation.

Use Case: Distributing resources across a fixed set of Availability Zones (AZs). For example, if you have 10 instances but only 3 AZs, element will cycle through them (1→AZ1, 2→AZ2, 3→AZ3, 4→AZ1...).


💻 Syntax

element(list, index)

💡 Examples

1. Basic Access:

# Result: "b"
output "second_item" {
  value = element(["a", "b", "c"], 1)
}

2. The "Wrap-Around" Feature (Cycling):

If the list has 3 items (index 0, 1, 2) and you ask for index 3, it goes back to 0.

locals {
  azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
}

# Result: "us-east-1a" (3 % 3 = 0)
output "fourth_item" {
  value = element(local.azs, 3)
}

3. Practical Scenario: High Availability

Distributing instances across zones automatically:

resource "aws_instance" "web" {
  count = 5

  # This will assign AZs in order: a, b, c, a, b
  availability_zone = element(var.az_list, count.index)
}

⚠️ Key Details

  • Strings/Numbers: Works with any type of data inside the list.

  • Empty Lists: Unlike many other functions, calling element on an empty list will result in an error because there's nothing to wrap around.

  • Negative Indices: In newer versions of Terraform, negative indices are supported (e.g., -1 gets the last element).


  • [[lookup]] — The equivalent for maps.

  • [[index]] — The opposite: finds the index of a specific value.

  • Official HashiCorp Docs