length tells you how big something is: how many items a list or map holds, or how many characters a string has. It’s how a configuration checks that a list isn’t empty or that a name isn’t too long.
Syntax
length(<VALUE>)
<VALUE>: a list, a map or a string. For a list or a map, the result is the number of items; for a string, the number of characters.
The function is described in length Function (opens in a new tab) in the OpenTofu® docs.
Prerequisites
- OpenTofu installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
Step 1: Try It in tofu console
Open a terminal in any empty folder and start tofu console, which evaluates expressions as you type them:
tofu console
Type each expression and press Return (Enter on Windows and Linux) to see its value:
> length(["red", "green", "blue"])
3
> length({ tea = 2, cake = 3 })
2
> length("hello")
5
> length("Café")
4
> 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 |
|---|---|---|
Expecting length to count bytes | It counts characters: length("Café") is 4, although the é takes two bytes. | Use it as a character count. |
Comparing a list with [] to see whether it’s empty | The docs explain that [] is a tuple, so the comparison is never true. | Write length(var.list) == 0. |
FAQ
Does length work on a number?
No. It accepts a list, a map, a string or another collection; for a number, OpenTofu stops with an error.
Where is length most useful?
In checks, such as a variable’s validation block that requires at least one item or a name of at most 80 characters.
Conclusion
length(<VALUE>) returns the number of items in a list or map, or the number of characters in a string.
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.
0 comments