How do you validate input variables in terraform?

This is an experimental feature, which means you have to specify the following inside your variables.tf (or wherever your variables are defined):

terraform {
  experiments = [variable_validation]
}

Simply use a validation block and use whatever condition (can be a simple string contains or a more complicated regex).

Example – validate that my domain name starts with www.

variable "mydomainname" {

validation {
  condition = length(regexall("^www", mydomainname)) > 0
  error_message = "Should start with www"
  }
}

To use regex – you actually need to use regexall – this is what returns the COUNT of how many matches the regex found (regex, by itself, returns only the matching characters). For a full list of regex patterns supported by terraform

Current Limitations (Only single variable validation)

Unfortunately, in it’s current experimental version, terraform does not support passing in a variable into the ‘condition’ statement. The condition HAS to take in the input variable name exactly (i.e. – it cannot accept an each.value).

This code WILL NOT work

variable "mytestdomainnames" {

listnames = split(",",var.mytestdomainnames)

for_each = var.listnames

validation {
condition = length(regexall("^www", each.value)) > 0
error_message = "Should start with www"
  }
}

If you cannot use the validation block

Here is a workaround that I used prior to the introduction of the validation block in terraform. A null resource which prints an error if something doesn’t evaluate to true.

variable "mydomainname" {

}

resource "null_resource" "nullres" {

testval = "${length(regexall("^www", var.mydomainname)) > 0 ? 0 : 1}"
"ERROR: Must start with www" = true
}

Summary

The validation block in terraform is a necessary new feature. When combined with a regex or regexall, it can pretty much validate any kind of input pattern (see this list of full regex patterns).
Unfortunately, while it is great for single variable validation, it does not support any kind of looping or multi valued validation.

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.