Skip to main content
0 reactions

How to Use the length Function in OpenTofu

Card titled The length Function, labelled OpenTofu Functions, showing length([red, green, blue]) and the result 3.
Count the items in an OpenTofu list or map, or the characters in a string, with the length function

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

SyntaxHCL
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

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:

TerminalBash
tofu console

Type each expression and press Return (Enter on Windows and Linux) to see its value:

tofu consolePlain text
> 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

MistakeWhat happensDo this instead
Expecting length to count bytesIt 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 emptyThe 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