【问题标题】:How to validate a character set in terraform variable?如何验证 terraform 变量中的字符集?
【发布时间】:2022-04-23 11:14:28
【问题描述】:

我需要验证 terraform 中的变量。变量的内容应该只有0-9、a-z和A-Z。我用下面的代码试了一下:

variable "application_name" {
    type = string
    default = "foo"

    validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("([0-9A-Za-z])", var.application_name))
    error_message = "For the application_name value only a-z, A-Z and 0-9 are allowed."
  }
}

它不起作用。当我在变量中设置 abcd- 时,验证返回 true。

如何修复正则表达式?

感谢您的帮助;)


@vgersh99 这对我不起作用:

variable "application_name" {
    type = string
    default = "foo"

    validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("[^[:alnum:]]", var.application_name))
    error_message = "For the application_name value only a-z, A-Z and 0-9 are allowed."
  }
}

这是错误:

$ terraform validate
Error: Invalid value for variable
  on main.tf line 23, in module "ecs_cluster":
  23:   application_name = "frdlso"
For the application_name value only a-z, A-Z and 0-9 are allowed.
This was checked by the validation rule at
.terraform/modules/ecs_cluster/variables.tf:34,5-15

【问题讨论】:

  • 你不是说[^[:alnum:]]吗?

标签: regex terraform


【解决方案1】:

regex 函数尝试将给定字符串的 子字符串 与指定模式进行匹配,因此只要有 至少一个,第一个示例中的模式就会成功/em> 输入中的 ASCII 数字或字母。

要实现您描述的规则,您需要扩展模式以覆盖整个字符串。 the regular expression syntax 的三个部分可以一起使用来实现:

  • ^ 符号仅匹配给定字符串的开头。
  • $ 符号仅匹配给定字符串的末尾。
  • + 运算符允许前面的模式出现一次或多次次。

将它们放在一起,我们得到模式^[0-9A-Za-z]+$:字符串的开头,后跟一个或多个 ASCII 字母或数字,然后是字符串的结尾。因此,该模式只有在整个字符串都匹配时才会成功。

将其放入您的完整示例中将为我们提供以下信息:

variable "application_name" {
    type = string
    default = "foo"

    validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("^[0-9A-Za-z]+$", var.application_name))
    error_message = "For the application_name value only a-z, A-Z and 0-9 are allowed."
  }
}

【讨论】:

    【解决方案2】:

    除了 Martin 的响应之外,还有具有相同行为的简写 [[:alnum:]]

    condition = can(regex("^[[:alnum:]]+$", var.application_name))
    

    来自链接的docs

    [[:alnum:]] 同 [0-9A-Za-z]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-09
      • 2013-07-15
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      相关资源
      最近更新 更多