We’re excited to announce that custom variable validation is being released as a production-ready feature in Terraform 0.13. Custom Variable Validation was introduced as a language experiment in Terraform 0.12.20 and builds upon the type system introduced in Terraform 0.12 by allowing configurations to contain validation conditions for a given variable.
In the example below, we define a condition for the variable ami_id
which requires the id to begin with the string ami
:
variable "ami_id" {
type = string
validation {
condition = (
length(var.ami_id) > 4 &&
substr(var.ami_id, 0, 4) == "ami-"
)
error_message = "The ami_id value must start with \"ami-\"."
}
}
Each variable
block can have zero or more validation
blocks, allowing an author to potentially write a specific error message associated with each distinct check.
The condition
expression is evaluated in a reduced evaluation context that supports all of Terraform's built-in functions but allows referring only to the variable being validated — in this case, var.ami_id
— which evaluates to the value given by the caller after any automatic conversion to the given type constraint string
. The expression can therefore safely assume var.ami_id
is a string in this case.
If the expression returns true
then the validation is considered to have succeeded. If it returns false
then validation has failed and Terraform will return an error at the module call site, using the text given in error_message
:
Error: Invalid value for variable
on variable-validation-rfc.tf line 4, in module "example":
4: ami_id = "amo-abc123"
The ami_id value must start with "ami-".
This was checked by the validation rule at example/variables.tf:4,3-13.
Terraform’s custom variable validation takes the ergonomics of this feature one step further and will distinguish between an error produced by validation of the variable itself or an error with the expression used as the condition for validation. More information is available in the Terraform documentation.
Download the latest Terraform 0.13 pre-release today and give custom variable validation a try. Don’t forget to join us on our community forums for questions and discussion about this and the other new features of Terraform 0.13.
Terraform Enterprise now supports more flexible deployment options for self-hosted environments, including cloud-managed Kubernetes services.
Assigning agents at the organization level provides a faster, more consistent, and scalable approach to agent pool configuration.
Learn how creating a golden image pipeline can help unify and streamline your imaging and provisioning workflows throughout your infrastructure estate.