Site icon JD Bots

How to Read List Elements and Object Attributes in OpenTofu

Card titled List Elements and Attributes, labelled OpenTofu Basics, showing local.user.name and the result Ana.

Read one item from an OpenTofu list, map or object with square brackets or a dot

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>

The rules are in Indices and Attributes in the OpenTofu® docs.

Prerequisites

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

MistakeWhat happensDo this instead
Counting list positions from 1The 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 teaA 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.

Exit mobile version