Sam
Sam

Reputation: 873

Regular expressions in Terraform

I need to use regular expressions in my Terraform code. The documentation for the replace function says the string if wrapped in a forward slash can be treated as a regex.

I've tried the following:

Name = "${replace(var.string, var.search | lower(var.search), replace)}"

I need to use regex to replace either the string or the lower case of the string with the replace string.

Upvotes: 14

Views: 53747

Answers (5)

Sarkom
Sarkom

Reputation: 853

I created a Go Playground link: https://go.dev/play/p/T3KGburfZcw that emulates the replace function. I am using an older version of Terraform, but it should still work for newer versions. Hope this is helpful for others that have struggled to debug a regex.

Upvotes: 1

Ualter Jr.
Ualter Jr.

Reputation: 2438

Just to help someone else looking here... following the Terraform documentation: https://www.terraform.io/docs/language/functions/replace.html

To be recognized as a Regex, you need to put the pattern between / (slashes), like this:

 > replace("hello world", "/w.*d/", "everybody")
 > hello everybody

Upvotes: 2

user182159
user182159

Reputation: 21

I think it is: "${replace(var.string, "/\\.$/", "")}"

Upvotes: 1

Xtigyro
Xtigyro

Reputation: 421

One more example - removing the period from the end of the "string" variable:

variable "string"  { default = "Foo." }

"${replace("var.string", "\\.$", "")}"

Upvotes: 4

ydaetskcoR
ydaetskcoR

Reputation: 56997

The Terraform docs for the replace function state that you need to wrap your search string in forward slashes for it to search for a regular expression and this is also seen in the code.

Terraform uses the re2 library to handle regular expressions which does supposedly take a /i flag to make it case insensitive. However I couldn't seem to get that to work at all (even trying /search/i/) but it does support Perl style regular expressions unless in POSIX mode so simply prefixing your search variable with (?i) should work fine.

A basic worked example looks like this:

variable "string"  { default = "Foo" }
variable "search"  { default = "/(?i)foo/" }
variable "replace" { default = "bar" }

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"

  tags {
    Name = "${replace(var.string, var.search, var.replace)}"
  }
}

Upvotes: 24

Related Questions