如何解决Terraform 13,根据另一个值验证变量
有没有一种实现以下逻辑的方法
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.
解决方法
虽然有一个 Github issue 来实现这个功能,但验证多个变量的唯一方法是使用局部变量在运行时抛出错误:
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
: "" ) )
}
这是一个凌乱、粗略的 hack,但它应该可以防止应用无效值。
,由于您无法引用特定变量之外的其他变量,因此可以将其用作列表以不同的方式进行操作:
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."
}
}
,
我为自己找到的类似问题的最佳解决方案是将支票放入模块中。 只有当环境需要设置变量时,才会包含所述模块。
module input_validation {
source = "./modules/input_validation"
count = var.environment == "test" ? 1 : 0
fet_code = var.fet_code
}
然后在 modules/input_validation/input_validation.tf 中:
variable "fet_code" {
default = ""
type = string
validation {
condition = length(var.fet_code) != 3
error_message = "The environment has been set to 'test' but the fet_code has not be defined."
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。