How to Use the element Function in Terraform
In Terraform, the
element function returns an item from a list at a given index, automatically wrapping the index if it is out of range. Use element(list, index) to safely get elements without errors from invalid indexes.Syntax
The element function takes two arguments: a list and an index. It returns the element at the given index, wrapping around if the index is larger than the list size.
- list: A list of values to select from.
- index: The position of the element to retrieve. If this is out of range, it wraps around.
terraform
element(list, index)
Example
This example shows how element safely accesses list items even if the index is larger than the list length by wrapping around.
terraform
variable "colors" { default = ["red", "green", "blue"] } output "color_0" { value = element(var.colors, 0) } output "color_3" { value = element(var.colors, 3) } output "color_4" { value = element(var.colors, 4) }
Output
color_0 = "red"
color_3 = "red"
color_4 = "green"
Common Pitfalls
Common mistakes include using direct list indexing which can cause errors if the index is out of range. element avoids this by wrapping the index. Also, remember element only works with lists, not maps or sets.
terraform
/* Wrong: direct indexing can fail if index is out of range */ output "wrong_access" { value = var.colors[4] # Error: index out of range } /* Right: element wraps index safely */ output "right_access" { value = element(var.colors, 4) # Returns "green" }
Quick Reference
| Function | Description | Example |
|---|---|---|
| element(list, index) | Returns element at index, wraps if out of range | element(["a", "b", "c"], 4) → "b" |
| list[index] | Direct access, errors if index out of range | ["a", "b", "c"][4] → error |
Key Takeaways
Use element(list, index) to safely access list items with automatic index wrapping.
Direct list indexing can cause errors if the index is out of range; element avoids this.
element only works with lists, not with maps or sets.
Index wrapping means indexes larger than the list length start again from the beginning.
Use element to cycle through list values without worrying about index errors.