Sling Academy
Home/DevOps/Terraform: How to replace all occurrences of a substring in a string

Terraform: How to replace all occurrences of a substring in a string

Last updated: February 03, 2024

Introduction

In the world of Infrastructure as Code (IaC), Terraform stands out for its powerful and declarative syntax that lets you describe your cloud infrastructure using high-level configuration files. One frequent operation when working with Terraform and its HCL (HashiCorp Configuration Language) is string manipulation, especially the need to replace all occurrences of a substring within a string. This can be crucial for dynamically generating resource names, altering configurations without manual intervention, and many other use cases where textual content needs to be programmatically adjusted.

This tutorial will guide you through replacing all occurrences of a substring in a string in Terraform, progressing from the most basic methods to more advanced techniques. We’ll also include code examples and explain outputs where applicable to ensure you can apply what you learn effectively.

Basic Substring Replacement in Terraform

Let’s start with the most straightforward scenario where you need to replace a specific substring within a string. Terraform provides a built-in function replace for this purpose. The syntax for this function is replace(input, search, replace), where input is the original string, search is the substring you want to replace, and replace is the string you want to insert in place of the search substring.

Example 1: Basic Replacement

variable "example_string" {
  description = "A sample string for replacement"
  default     = "This is a test string."
}

output "replaced_string" {
  value = replace(var.example_string, " test", " successful")
}

In this example, we replaced ” test” with ” successful” in the variable example_string. The output will be: This is a successful string..

Using Regular Expressions for Substring Replacement

The replace function also accepts regular expressions (regex) for the search parameter, offering a more flexible and powerful approach to substring replacement. With regex, you can match patterns within the string instead of fixed substrings, enabling complex replacements.

Example 2: Replacement Using Regex

output "regex_replaced_string" {
  value = replace(var.example_string, "\\btest\\b", "experiment")
}

In this example, we use the regular expression \\btest\\b to match the word “test” as a whole word, not part of another word, and replace it with “experiment”. The output will be: This is a experiment string..

Advanced String Manipulation

While the replace function is powerful, sometimes your string manipulation requirements might go beyond simple replacement. Terraform does not natively include a comprehensive string manipulation library, but you can combine its basic functions creatively to achieve complex results.

Example 3: Combining Functions for Complex Manipulations

locals {
  original_string = "Hello, World! Welcome to Terraform."
  step1 = replace(local.original_string, "World", "Terraform Users")
  step2 = replace(step1, "Terraform.", "our great tool.")
}

output "complex_replaced_string" {
  value = local.step2
}

This example demonstrates combining multiple replace operations to perform complex text manipulations. The output is “Hello, Terraform Users! Welcome to our great tool.”.

Conclusion

String replacement in Terraform using the replace function, especially when combined with regular expressions, is a powerful method for dynamic configuration updates. This guide has shown you how to conduct basic to advanced substring replacements in Terraform, providing practical examples at each step. By understanding these techniques, you can harness the full potential of Terraform for your infrastructure management and automation tasks.

Next Article: Terraform: How to add/remove elements from a list

Previous Article: Terraform: How to check if a string contains a substring

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide