Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform - Specifying multiple possible values for Variables

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"
        ]
   }
like image 703
seou1 Avatar asked Jan 18 '19 12:01

seou1


People also ask

How do you pass multiple values to a variable in Terraform?

There are two methods supported for doing this using the Terraform CLI when running Terraform commands. -var flag enables a single input variable value to be passed in at the command-line. -var-file flag enables multiple input variable values to be passed in by referencing a file that contains the values.

Can Terraform output have multiple values?

You can have multiple resources in a single output, but to make it work, you need to use some terraform function, or format the output depending on the type, if it is a list, string, map..

How do you assign a value to a variable in Terraform?

Additionally, input variable values can also be set using Terraform environment variables. To do so, simply set the environment variable in the format TF_VAR_<variable name> . The variable name part of the format is the same as the variables declared in the variables.tf file.

Can we have multiple variable files in Terraform?

To deploy the multi-file configuration, I just need to start a regular plan, apply or destroy task. Terraform will find all the tf. -files, merge them and then executes. If a variables file should be used, the parameter –var-file is needed to point Terraform to the file.


1 Answers

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."
  }
}
like image 184
Adil B Avatar answered Nov 15 '22 09:11

Adil B