terraformterraform-provider-aws

Terraform 13, Validate variable base on the value of another


Is there a way of implementing the below logic

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

At the moment i get the following error:

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.

I understand what the problem is with the code, I am just wondering if there is a way round the restriction?


Solution

  • While there's a Github issue for implementing this as a feature, the only way to validate against multiple variables is by using locals to throw an error at runtime:

    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
            : "" ) )
    }
    

    It's a messy, sketchy hack, but it should prevent invalid values from getting applied.