Regular expressions in Terraform

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)}"
  }
}

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

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


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

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

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