Skip to content

Function replace()

📝 Description

The replace function searches a string for a specific substring (or a regular expression) and replaces it with another string.

Use Case: Converting "Human Readable" names into "Cloud Compatible" names. For example, changing My Web Server to my-web-server.


💻 Syntax

replace(string, search, replace)
  • string: The original text.

  • search: What you are looking for (can be a simple string or a Regex).

  • replace: What you want to put in its place.


💡 Examples

1. Simple Character Replacement:

Swapping spaces for hyphens to create a valid URL or resource name.

# Result: "production-vpc-01"
output "resource_name" {
  value = replace("production vpc 01", " ", "-")
}

2. Using Regular Expressions (Regex):

You can use forward slashes /.../ to indicate a regex pattern. This example removes all non-alphanumeric characters.

# Result: "appserver01" (removes the '#' and '!')
output "cleaned_id" {
  value = replace("app#server!01", "/[^a-zA-Z0-9]/", "")
}

3. Practical Scenario: Domain Formatting

If you have a variable that might contain a protocol (http://) but your resource only needs the domain:

variable "website_url" { default = "http://example.com" }

locals {
  # Result: "example.com"
  domain_only = replace(var.website_url, "http://", "")
}

⚠️ Important Note

  • If the search string is not found, the function returns the original string without an error.

  • replace will replace all occurrences of the search string, not just the first one.


  • [[split]] — Break a string into a list based on a character.

  • [[trim]] — Remove characters only from the start and end.

  • Official HashiCorp Docs