Terraform - Specifying multiple possible values for Variables

22.7k views Asked by At

CloudFormation provides AllowedValues for Parameters which tells that the possible value of the parameter can be from this list. How can I achieve this with Terraform variables? The variable type of list does not provide this functionality. So, in case I want my variable to have value out of only two possible values, how can I achieve this with Terraform. CloudFormation script that I want to replicate is:

"ParameterName": {
        "Description": "desc",
        "Type": "String",
        "Default": true,
        "AllowedValues": [
            "true",
            "false"
        ]
   }
3

There are 3 answers

1
Adil B On BEST ANSWER

I don't know of an official way, but there's an interesting technique described in a Terraform issue:

variable "values_list" {
  description = "acceptable values"
  type = "list"
  default = ["true", "false"]
}

variable "somevar" {
description = "must be true or false"
}

resource "null_resource" "is_variable_value_valid" {
  count = "${contains(var.values_list, var.somevar) == true ? 0 : 1}"
  "ERROR: The somevar value can only be: true or false" = true
}

Update:

Terraform now offers custom validation rules in Terraform 0.13:

variable "somevar" {
  type = string
  description = "must be true or false"

  validation {
    condition     = can(regex("^(true|false)$", var.somevar))
    error_message = "Must be true or false."
  }
}
0
famzah On

Custom validation rules is definitely the way to go. If you want to keep things simple and check the provided value against a list of valid ones, you can use the following in your variables.tf config:

variable "environment" {
  type = string
  description = "Deployment environment"
  validation {
    condition = contains(["dev", "prod"], var.environment)
    error_message = "Valid value is one of the following: dev, prod."
  }
}
1
user2848199 On

Variation on the above answer to use an array/list.

variable "appservice_sku" {

    type        = string 
    description = "AppService Plan SKU code"
    default     = "P1v3"

    validation {
        error_message = "Please use a valid AppService SKU."
        condition = can(regex(join("", concat(["^("], [join("|", [ 
            "B1", "B2", "B3", "D1", "F1", 
            "FREE", "I1", "I1v2", "I2", "I2v2", 
            "I3", "I3v2", "P1V2", "P1V3", "P2V2", 
            "P2V3", "P3V2", "P3V3", "PC2", 
            "PC3", "PC4", "S1", "S2", "S3", 
            "SHARED", "WS1", "WS2", "WS3"
        ])], [")$"])), var.appservice_sku))
    }
}