Site icon JD Bots

How to Use the trimspace Function in OpenTofu

Card titled The trimspace Function, labelled OpenTofu Functions, showing trimspace( hello ) and the result hello.

Remove the spaces and line breaks around an OpenTofu string with trimspace, and see which spaces it keeps

trimspace removes the spaces around a string: at its start and at its end, including tabs and line breaks. It’s useful before you check whether a value is empty, or when text comes from a file with a final line break.

Syntax

Syntax

trimspace(<STRING>)

The docs say it follows the Unicode definition of a space, so line breaks and tabs count too: trimspace Function.

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:

Terminal

tofu console

Type each expression to see what it removes. The last one puts the result between brackets, so the kept spaces show:

tofu console

> trimspace("  hello  ")
"hello"
> trimspace("\n  hello world\n")
"hello world"
> "[${trimspace("   a   b   ")}]"
"[a   b]"
> 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 spaces inside a string to goOnly the start and end are trimmed: "a b" keeps its three spaces.Use replace to change spaces inside a string.
Checking var.name == "" to reject an empty nameA name made only of spaces passes the check.Check trimspace(var.name) == "" instead.

FAQ

Does trimspace change the original value?

No. It returns a new string; the variable keeps its value.

Does it remove line breaks?

Yes, at the start and the end: the docs count them as spaces.

Conclusion

trimspace(<STRING>) returns the string without the spaces, tabs and line breaks at its start and end.

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