Skip to main content
0 reactions

How to Use the distinct Function in OpenTofu

Card titled The distinct Function, labelled OpenTofu Functions, showing distinct([tea, cake, tea]) and the result tolist([tea, cake]).
Remove repeated values from an OpenTofu list with distinct, keeping the first of each in its original order

distinct removes repeated values from a list. Comparing its length with the original list’s length also tells you whether the list had duplicates.

Syntax

SyntaxHCL
distinct(<LIST>)
  • <LIST>: the list to clean up. The docs say the first occurrence of each value is kept, in the original order.

The function is described in distinct 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 to see the result:

tofu consolePlain text
> distinct(["tea", "cake", "tea", "jam", "cake"])
tolist([
  "tea",
  "cake",
  "jam",
])
> distinct([3, 1, 3, 2, 1])
tolist([
  3,
  1,
  2,
])
> 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 the result to be sortedIt keeps the original order of the first occurrences.Sort it separately if you need an order.
Expecting "Tea" and "tea" to count as the sameThey’re different values, so both stay.Make them the same case first, for example with lower.

FAQ

How do I check that a list has no duplicates?

Compare lengths: when length(distinct(var.names)) == length(var.names) is true, every name is unique.

Why does the result say tolist?

The console shows that the result is a list; its values are the ones you see.

Conclusion

distinct(<LIST>) returns the list with each value once, in the order they first appear.

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