To use one value from a collection, you point at it: square brackets with a number for a list, square brackets with a key for a map, or a dot and a name for an object’s attribute.
Syntax
Syntax
<LIST>[<INDEX>]
<MAP>["<KEY>"]
<OBJECT>.<ATTRIBUTE>
<INDEX>: the position in a list, starting at 0.<KEY>: a map’s key, as text.<ATTRIBUTE>: an attribute’s name. The docs say the dot works for names that are valid identifiers; brackets work for any key.
The rules are in Indices and Attributes in the OpenTofu® docs.
Prerequisites
- OpenTofu installed. Installing OpenTofu in the OpenTofu docs covers every system.
Step 1: Create a Small Configuration
In an empty folder, create main.tf with a list, a map and an object:
main.tf
locals {
colors = ["red", "green", "blue"]
prices = {
tea = 2
cake = 3
}
user = {
name = "Ana"
role = "admin"
}
}
Step 2: Try It in tofu console
This configuration uses no providers, so the console works without tofu init. Start it in the folder:
Terminal
tofu console
Type each expression to see the value. The last one asks for a fourth color:
tofu console
> local.colors[0]
"red"
> local.colors[2]
"blue"
> local.prices["cake"]
3
> local.user.name
"Ana"
> local.user["role"]
"admin"
> local.colors[3]
╷
│ Error: Invalid index
│
│ on <console-input> line 1:
│ (source code not available)
│
│ The given key does not identify an element in this collection value: the given index is greater than or equal to the length of the collection.
╵
> exit
Clean Up
Type exit to leave the console. The example creates nothing, so there’s nothing else to remove.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Counting list positions from 1 | The first item is [0], so [3] asks for a fourth item. | Count from 0. |
Using a dot with a key that has a space, such as green tea | A dot can’t name a key with a space. | Use brackets: local.prices["green tea"]. |
FAQ
How do I get the last item of a list?
Use length: local.colors[length(local.colors) - 1].
Can I read the same attribute from every item?
Yes, a splat expression does it: var.users[*].name.
Conclusion
Read a list item with [<INDEX>] from 0, a map value with ["<KEY>"], and an object attribute with a dot.
Additional Resources
OpenTofu® is a registered trademark of LF Projects, LLC. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by the OpenTofu project.
