Terraform 13,根据另一个变量的值验证变量
是否有实现以下逻辑的方法Terraform 13,根据另一个变量的值验证变量,terraform,terraform-provider-aws,Terraform,Terraform Provider Aws,是否有实现以下逻辑的方法 variable "environment" { description = "The environment this will be run in can only be set to [preprod|test|prod]" type = string default = "test" validation { condition = can(rege
variable "environment" {
description = "The environment this will be run in can only be set to [preprod|test|prod]"
type = string
default = "test"
validation {
condition = can(regex("^(prod|preprod|test)$", var.environment))
error_message = "The environment variable can only be set to [prod|preprod|test]."
}
}
variable "fet_code" {
description = "Set the feature code"
type = string
default = ""
validation {
condition = var.environment == "test" && length(var.fet_code) != 3
error_message = "The environment has been set to 'test' but the fet_code has not be defined."
}
}
目前,我得到以下错误:
Error: Invalid reference in variable validation
on variable.tf line 17, in variable "fet_code":
17: condition = var.environment == "fet" && length(var.fet_code) == 3
The condition for variable "fet_code" can only refer to the variable itself,
using var.fet_code.
我理解代码的问题所在,我只是想知道是否有办法绕过限制?由于您不能引用特定变量之外的其他变量,您可以使用另一种方式将其用作列表:
variable "fet_code" {
description = "Set the feature code"
type = list
default = ["test", ""]
validation {
condition = var.fet_code[0] == "test" && length(var.fet_code[1]) != 3
error_message = "The environment has been set to 'test' but the fet_code has not be defined."
}
}
虽然有一种方法可以将其作为功能实现,但针对多个变量进行验证的唯一方法是使用局部变量在运行时抛出错误:
variable "environment" {
description = "The environment this will be run in can only be set to [preprod|test|prod]"
type = string
default = "test"
validation {
condition = can(regex("^(prod|preprod|test)$", var.environment))
error_message = "The environment variable can only be set to [prod|preprod|test]."
}
}
variable "fet_code" {
description = "Set the feature code"
type = string
default = ""
}
locals {
validate_fet_code_cnd = var.environment == "test" && length(var.fet_code) != 3
validate_fet_code_msg = "The environment has been set to 'test' but the fet_code has not been defined."
validate_fet_code_chk = regex(
"^${local.validate_fet_code_msg}$",
( !local.validate_fet_code_cnd
? local.validate_fet_code_msg
: "" ) )
}
这是一个混乱、粗略的破解,但它应该可以防止应用无效值。不清楚您试图从该
fet_代码
条件中实现什么;你能澄清一下吗?另外,根据环境
上的条件
,如果该变量不是允许的输入值,为什么要检查环境
变量是否等于功能
?@MattSchuchard感谢您指出错误。我想我解决了所有的问题。我试图编码的逻辑是,如果变量环境
设置为测试
,则必须设置变量fet_code
,否则应为空OK,因此这是不可能的,因为变量的值不能在变量声明中使用,但如果是这样,您将使用三元组来控制true
/false
返回,例如:var.environment==“test”?(长度(变量fet_代码)==3):真
。注意:您还切换了true
/false
返回值,以便对fet\u代码长度进行验证。