Terraform 13,根据另一个值验证变量

时间:2020-08-28 08:11:20

标签: 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(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.

我了解代码的问题所在,我只是想知道是否存在解决限制的方法?

3 个答案:

答案 0 :(得分:3)

虽然有一个 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,但它应该可以防止应用无效值。

答案 1 :(得分:0)

由于您无法引用特定变量之外的其他变量,因此可以将其用作列表以不同的方式进行操作:

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."
  }
}

答案 2 :(得分:0)

我为自己找到的类似问题的最佳解决方案是将支票放入模块中。 只有当环境需要设置变量时,才会包含所述模块。

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."
  }
}
相关问题