我需要验证 terraform 中的变量。变量的内容只能是0-9、az和AZ。我尝试使用以下代码:
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."
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用。当我在变量中设置 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."
}
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
$ 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
Run Code Online (Sandbox Code Playgroud)
Mar*_*ins 22
该函数尝试将给定字符串的子字符串regex与指定模式进行匹配,因此只要输入中至少有一个ASCII 数字或字母,第一个示例中的模式就会成功。
要实现您所描述的规则,您需要扩展模式以覆盖整个字符串。您可以一起使用正则表达式语法的三个部分来实现此目的:
^符号仅在给定字符串的开头匹配。$符号仅在给定字符串的末尾匹配。+符允许前面的模式出现一次或多次。将它们放在一起,我们得到以下模式^[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."
}
}
Run Code Online (Sandbox Code Playgroud)
除了马丁的回应之外,还有[[:alnum:]]具有相同行为的简写:
condition = can(regex("^[[:alnum:]]+$", var.application_name))
Run Code Online (Sandbox Code Playgroud)
从链接的文档:
[[:alnum:]] 与 [0-9A-Za-z] 相同