Skip to main content
0 reactions

How to Use the replace Function in OpenTofu

Card titled The replace Function, labelled OpenTofu Functions, showing replace(1 + 2 + 3, +, -) and the result 1 - 2 - 3.
Change every occurrence of some text in an OpenTofu string with replace, using plain text or a regular expression

replace finds some text in a string and changes every place it appears. Wrap the search text in slashes, and it becomes a regular expression.

Syntax

SyntaxHCL
replace(<STRING>, <SEARCH>, <REPLACEMENT>)
  • <STRING>: the text to change.
  • <SEARCH>: the text to find. Every occurrence is replaced. Written as /…/, it’s a regular expression.
  • <REPLACEMENT>: the new text. With a regular expression, $1 and similar insert captured groups.

The function is described in replace 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. The last one uses a regular expression:

tofu consolePlain text
> replace("1 + 2 + 3", "+", "-")
"1 - 2 - 3"
> replace("Tea & Biscuits", "&", "and")
"Tea and Biscuits"
> replace("hello world", "/w.*d/", "everybody")
"hello everybody"
> 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 only the first occurrence to changeEvery occurrence is replaced.Make the search text more specific if you need fewer changes.
Searching for text that starts and ends with a slashIt’s read as a regular expression.Escape it, or search for a part without the slashes.

FAQ

Can I chain replacements?

Yes. Put one inside another: replace(replace(s, "a", "b"), "c", "d").

Does replace change the variable?

No. It returns a new string.

Conclusion

replace(<STRING>, <SEARCH>, <REPLACEMENT>) returns the string with every match of the search text replaced.

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