[Webinar] How to effectively prove compliance in a multi-cloud, multi-IaC world

➡️ Register now

How to Use Terraform Replace Function [Examples]

terraform

🚀 Level Up Your Infrastructure Skills

You focus on building. We’ll keep you updated. Get curated infrastructure insights that help you make smarter decisions.

Terraform often involves dynamically generating resource names, tags, and configurations based on variables or external inputs. In real-world scenarios, these values may include characters or formats that aren’t compatible with certain cloud provider rules. 

To handle such situations, string manipulation becomes a key part of writing clean, reliable infrastructure code. In this article, we’ll explore how to use the Terraform replace function for that.

What is the Terraform replace function?

The replace function in Terraform returns a copy of a string with all matches of a substring replaced by a specified replacement string. If the substring is wrapped in forward slashes, it is treated as a regular expression. It’s useful when modifying strings for naming resources, formatting values, or cleaning up outputs.

It follows this syntax:

replace(string, pattern, replacement)

When using a regex the pattern must be wrapped like /your-pattern/ and the replacement supports backreferences using $1, $2 and so on.

Example 1: Simple replacement for resource naming

In this example, we want to replace all hyphens - with underscores _ in the env variable string.

variable "env" {
  default = "dev-environment"
}

output "clean_env_name" {
  value = replace(var.env, "-", "_")
}

The result will be:

dev_environment

This is commonly used to ensure compatibility in systems that don’t allow certain characters in resource names, such as AWS IAM role names or S3 bucket names.

  • "dev-environment" → original string
  • "-" → the substring to match
  • "_" → the replacement value

So every - is replaced with _. If your infrastructure has a naming convention that disallows dashes, this function quickly standardizes your inputs.

Example 2: Removing a prefix using regex

Here, we want to remove the prefix refs/tags/v from a Git reference string to extract just the version number.

variable "tag" {
  default = "refs/tags/v1.2.3"
}

output "version" {
  value = replace(var.tag, "/^refs\/tags\/v/", "")
}

The result will be:

1.2.3

"^refs/tags/v" is a regular expression:

  • ^ asserts the start of the string.
  • It matches the exact beginning "refs/tags/v".

The replacement string is empty "", meaning that the matched pattern is removed. Note the /…/ wrapper and the escaped slashes in the pattern.

This is especially useful in CI/CD pipelines where tags are fetched directly from Git, but only the semantic version (v1.2.3) is required for Docker images, labels, or release notes.

Tips for using the Terraform replace function

  • You can use replace() to strip characters, sanitize input, or build dynamic names.
  • By default replace() matches a literal substring. To use regex wrap the pattern in /…/.
  • If you want to replace literal characters, do not wrap the pattern and escape characters that have special meaning in HCL strings when needed.

Use case example: Sanitizing environment names for S3 buckets

In CI/CD pipelines, Git branch names like feature/add-logging are often used to create temporary or environment-specific resources. AWS S3 bucket names must be lowercase and can include letters, numbers, hyphens, and periods. They must be 3 to 63 characters and start and end with a letter or number.

To safely use a branch name in an S3 bucket, you can use Terraform’s replace() function to sanitize the string.

Here’s an example:

variable "branch_name" {
  type    = string
  default = "feature/add-logging"
}

resource "aws_s3_bucket" "env_bucket" {
  bucket = lower(replace(var.branch_name, "/[^a-z0-9.-]/", "-"))

  tags = {
    Environment = var.branch_name
  }
}

This code replaces all characters that are not letters, numbers, or hyphens with a hyphen using a regular expression. 

So, feature/add-logging becomes feature-add-logging, which is safe for use as a bucket name. The lower() function ensures the name is in lowercase, as required by S3. 

If you prefer to avoid periods for simplicity, you can use /[^a-z0-9-]/ instead.

Key points

Terraform’s replace() function modifies strings by replacing patterns as literal substrings by default or as regular expressions when the pattern is wrapped in /…/ using $1 style backreferences. It’s useful for sanitizing inputs, such as converting invalid characters in Git branch names to create compliant S3 bucket names.

Terraform is really powerful, but to achieve an end-to-end secure GitOps approach, you need to use a product that can run your Terraform workflows. Spacelift takes managing Terraform to the next level by giving you access to a powerful CI/CD workflow and unlocking features such as:

  • Policies (based on Open Policy Agent)
  • Multi-IaC workflows
  • Self-service infrastructure
  • Integrations with any third-party tools

If you want to learn more about Spacelift, create a free account today or book a demo with one of our engineers.

Note: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.

Manage Terraform better with Spacelift

Build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization and many more.

Learn more

Terraform Commands Cheat Sheet

Grab our ultimate cheat sheet PDF
for all the Terraform commands
and concepts you need.

Share your data and download the cheat sheet