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>)
<STRING>: the text to clean up. Spaces inside it stay as they are.
The docs say it follows the Unicode definition of a space, so line breaks and tabs count too: trimspace Function.
Prerequisites
- OpenTofu® installed. Installing OpenTofu 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:
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
| Mistake | What happens | Do this instead |
|---|---|---|
| Expecting the spaces inside a string to go | Only 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 name | A 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.
