Terraform 中的正则表达式

Regular expressions in Terraform

我需要在我的 Terraform 代码中使用正则表达式。 documentation for the replace function 表示如果用正斜杠包裹的字符串可以被视为正则表达式。

我试过以下方法:

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

我需要使用正则表达式将字符串或字符串的小写字母替换为替换字符串。

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 文档。

Terraform 使用 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 除非在 POSIX 模式下,因此只需在您的搜索变量前加上 (?i) 前缀就可以正常工作。

一个基本的工作示例如下所示:

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

再举一个例子 - 从 "string" 变量的末尾删除句点:

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

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

我认为是:"${replace(var.string, "/\.$/", "")}"

只是为了帮助其他人看这里...按照 Terraform 文档: https://www.terraform.io/docs/language/functions/replace.html

要被识别为正则表达式,您需要将模式放在 /(斜杠)之间,如下所示:

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