How to Replace Multiple Substrings in Terraform Using the replace Function
Nest multiple replace() calls for literal string substitutions, or use the map-based regexreplace() function (Terraform 1.5+) when replacing many patterns or groups with a common structure.
Terraform’s built-in replace function processes one substring substitution at a time. When your infrastructure code requires transforming several distinct literals within the same input, you must either chain multiple replace invocations or leverage regexreplace with a capture group and replacement map. According to the implementation in internal/lang/tfconf/functions.go, both functions evaluate strings sequentially during the expression parsing phase.
Nesting Multiple terraform replace Calls
The idiomatic approach for simple literal replacements is to nest replace calls, feeding the output of one function into the input of the next. Each invocation returns a new string, allowing you to substitute distinct targets in a pipeline.
This method is ideal when you have three or fewer distinct substrings to replace, as it maintains readability without introducing regex overhead:
replace(
replace(
replace(var.original, "foo", "bar"),
"baz", "qux"),
"hello", "world")
In this pattern, Terraform evaluates the innermost replace first, substituting "foo" with "bar", then passes that result to the next level to swap "baz" for "qux", and so on. The final output contains all substitutions applied sequentially.
Using regexreplace with a Replacement Map
For scenarios involving many literals or patterns that share a common structure, Terraform 1.5+ introduced a map-based overload for regexreplace. This accepts a regular expression with capture groups and a map that associates matched substrings with their replacements.
As documented in docs/language/functions/regexreplace.html and generated from website/docs/language/functions/regexreplace.html.markdown, this approach condenses multiple operations into one call:
locals {
replacements = {
"foo" = "bar"
"baz" = "qux"
"hello" = "world"
}
}
output "transformed" {
value = regexreplace(var.original, "(foo|baz|hello)", local.replacements)
}
The regex (foo|baz|hello) matches any of the three keys, and the function looks up each match in the map to determine its replacement value. This eliminates deep nesting and improves maintainability when managing large substitution lists.
Alternative: Looping with a for Expression
When substitutions are stored in a map variable and you need to apply them iteratively without using regexreplace, you can combine replace with a for expression. This technique processes the map keys sequentially, though it evaluates each replacement against the original string independently rather than cumulatively:
locals {
map = {
"one" = "1"
"two" = "2"
"three" = "3"
"four" = "4"
}
}
output "loop_replace" {
value = [
for k, v in local.map :
replace(var.original, k, v)
][length(local.map) - 1]
}
Note that this approach returns the result of the final map element applied to the original string, not a chain of cumulative transformations. For true sequential replacement, use nesting or regexreplace as shown above.
Choosing Between Nested replace and regexreplace
- Nested
replace: Best for two to three discrete literal strings. The logic is explicit, requires no regex knowledge, and compiles quickly according to the parser ininternal/lang/tfconf/functions.go. - Map-based
regexreplace: Best for four or more replacements, or when substrings follow a predictable pattern (e.g., all uppercase codes, all environment prefixes). This reduces configuration complexity and lines of code. - Performance: Both methods execute in microseconds during the plan phase; choose based on maintainability rather than speed.
Summary
- Nest
replacecalls when handling two to three specific literal substitutions in a single string. - Use
regexreplacewith a map (Terraform 1.5+) for four or more replacements, or when substrings follow a predictable pattern that can be expressed as a regular expression. - Avoid
forloops for cumulative string transformations unless each operation targets the original base string independently. - Reference
internal/lang/tfconf/functions.gofor the underlying Go implementation andwebsite/docs/language/functions/replace.html.markdownfor the public documentation source.
Frequently Asked Questions
Can I pass a list of replacements to a single terraform replace call?
No, the standard replace function only accepts a single substring and its replacement value. To process multiple substitutions, you must either nest multiple replace calls or use regexreplace with a capture group and replacement map. The function signature defined in internal/lang/tfconf/functions.go explicitly specifies these parameters as single string values, not collections.
Does nesting replace functions impact Terraform plan performance?
Nested replace calls have negligible performance impact for typical infrastructure code. Each call executes in microseconds using Go's native string manipulation libraries. However, excessively deep nesting (dozens of levels) can reduce configuration readability and slightly increase parsing time during the plan phase. For extensive substitution lists, prefer the map-based regexreplace approach.
How do I replace substrings conditionally based on their content?
Use regexreplace with a regular expression that captures the variable content, then supply a map where keys represent the possible matched values. If the match logic is too complex for a static map, wrap your replace calls in conditional expressions using Terraform’s ternary operator condition ? true_val : false_val, or preprocess the string using local values and for expressions before applying the replacement.
Where are the replace and regexreplace functions documented in the Terraform source?
The function implementations reside in internal/lang/tfconf/functions.go, while the HTML documentation sources are located at website/docs/language/functions/replace.html.markdown and website/docs/language/functions/regexreplace.html.markdown. These markdown files generate the official documentation pages at docs/language/functions/replace.html and docs/language/functions/regexreplace.html in the published Terraform documentation.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s https://instagit.com/install.md