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"
]
}
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.
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..
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.
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.
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."
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With