验证 Terraform 变量是否为字母数字字符串列表

Validate that a Terraform variable is a list of alphanumeric strings

提问人:Geert Smelt 提问时间:9/21/2023 更新时间:9/21/2023 访问量:87

问:

我正在尝试验证 Terraform 中的变量包含字母数字字符串列表。为此,我使用正则表达式并验证列表中的每个元素是否与此正则表达式匹配。

variable "list_of_strings" {
  type        = list(string)
  description = "List of alphanumeric strings (case-insensitive)"

  validation {
    condition = can(all([
      for value in var.list_of_strings : can(regex("^[A-Za-z0-9]*$", value))
    ]))
    error_message = "list_of_strings must contain only alphanumeric strings (case-insensitive)."
  }
}

然后,当我从这个 MWE 生成值为 的计划时,验证失败。["TEST"]

$ terraform plan -var 'list_of_strings=["TEST"]'
Planning failed. Terraform encountered an error while generating this plan.

╷
│ Error: Invalid value for variable
│
│   on variables.tf line 1:
│    1: variable "list_of_strings" {
│     ├────────────────
│     │ var.list_of_strings is list of string with 1 element
│
│ list_of_strings must contain only alphanumeric strings (case-insensitive).
│
│ This was checked by the validation rule at variables.tf:5,3-13.

我也尝试通过指定值,但结果保持不变。可能是什么问题?terraform.tfvars

正则表达式 验证 变量 terraform

评论


答:

1赞 Matthew Schuchard 9/21/2023 #1

这里的两个问题似乎是,你的外包装函数可能实际上是一个函数。此外,正则表达式字符可能旨在成为字符:can(all())alltrue()*+

condition = alltrue([
  for value in var.list_of_strings : can(regex("^[A-Za-z0-9]+$", value))
])

此外,如果你想稍微清理它,你可以替换它(TF DSL要求对这些字符进行双重转义)。\\w[A-Za-z0-9]

评论

0赞 Geert Smelt 9/21/2023
解决了验证问题。谢谢,也感谢其他建议。alltrue()