Variable validation rules in Terraform allow you to define custom constraints on input variables to ensure they meet specific criteria before Terraform processes the configuration. This feature helps catch configuration errors early and provides meaningful feedback to users.
Validation rules are d…Variable validation rules in Terraform allow you to define custom constraints on input variables to ensure they meet specific criteria before Terraform processes the configuration. This feature helps catch configuration errors early and provides meaningful feedback to users.
Validation rules are defined within a variable block using the validation sub-block. Each validation block requires two arguments: condition and error_message.
The condition argument is a boolean expression that must evaluate to true for the variable value to be considered valid. You can use any Terraform expression that returns a boolean, including built-in functions like length(), regex(), can(), and contains(). The expression references the variable using var.variable_name.
The error_message argument specifies the text displayed when validation fails. This message should clearly explain what constitutes a valid value, helping users correct their input.
Here is an example of a variable with validation:
variable "instance_type" {
type = string
description = "EC2 instance type"
validation {
condition = can(regex("^t[2-3]\\.", var.instance_type))
error_message = "Instance type must be a t2 or t3 series."
}
}
You can include multiple validation blocks for a single variable, and all conditions must pass for the value to be accepted. Validations run during the planning phase, preventing invalid configurations from being applied.
Key considerations include:
1. Validation expressions can only reference the current variable being validated
2. The condition must produce a boolean result
3. Error messages should be complete sentences starting with an uppercase letter
4. Use the can() function to gracefully handle expressions that might produce errors
Variable validation is particularly useful for enforcing naming conventions, restricting allowed values, validating formats like IP addresses or ARNs, and ensuring numeric values fall within acceptable ranges. This proactive approach improves configuration reliability and user experience.
Variable Validation Rules in Terraform
What are Variable Validation Rules?
Variable validation rules are a feature in Terraform that allows you to define custom validation logic for input variables. They enable you to specify conditions that variable values must meet before Terraform will proceed with any operations. This feature was introduced in Terraform 0.13 and provides a way to catch configuration errors early in the development cycle.
Why are Variable Validation Rules Important?
Variable validation rules are crucial for several reasons:
1. Early Error Detection: They catch invalid input values before Terraform attempts to create or modify infrastructure, preventing costly mistakes.
2. Self-Documenting Code: Validation rules serve as documentation, clearly indicating what values are acceptable for each variable.
3. Improved Security: They help enforce security policies by ensuring variables meet specific criteria (e.g., minimum password length, allowed regions).
4. Better Collaboration: Team members understand the constraints on variables, reducing misconfiguration errors.
How Variable Validation Rules Work
Validation rules are defined within variable blocks using the validation nested block. Each validation block requires two arguments:
condition: A boolean expression that must evaluate to true for the value to be valid.
error_message: A string that will be displayed when the condition evaluates to false.
Syntax Example:
variable "instance_type" { type = string description = "EC2 instance type" validation { condition = can(regex("^t2\\.", var.instance_type)) error_message = "Instance type must be a t2 type." }}
Key Functions Used in Validation:
- can(): Returns true if the expression evaluates successfully - regex(): Matches a string against a regular expression - length(): Returns the length of a string, list, or map - contains(): Checks if a list contains a specific value
Multiple Validation Blocks:
You can define multiple validation blocks for a single variable. All conditions must pass for the variable value to be considered valid.
variable "bucket_name" { type = string
validation { condition = length(var.bucket_name) >= 3 error_message = "Bucket name must be at least 3 characters." } validation { condition = length(var.bucket_name) <= 63 error_message = "Bucket name must not exceed 63 characters." }}
Exam Tips: Answering Questions on Variable Validation Rules
1. Remember the Required Arguments: Every validation block must have both condition and error_message. Questions may test whether you know both are mandatory.
2. Understand the condition Expression: The condition must evaluate to a boolean (true or false). It can only reference the variable being validated using var.variable_name.
3. Know the can() Function: The can() function is commonly used in validation rules to check if an expression would succeed. Exam questions often feature this function.
4. Error Message Requirements: The error_message should be a complete sentence starting with an uppercase letter and ending with a period. While not enforced, this is a best practice that may appear in questions.
5. Self-Reference Only: Validation conditions can only reference the variable being validated, not other variables or resources. This is a common exam topic.
6. Version Awareness: Remember that validation rules require Terraform 0.13 or later. Questions may reference version compatibility.
7. Multiple Validations: Know that multiple validation blocks are allowed and all must pass. Questions may ask about behavior when one validation fails.
8. When Validation Runs: Validation occurs during the planning phase, after variable values are determined but before resource operations begin.
9. Null Values: If a variable has a default value of null and no value is provided, the validation still runs. Plan your conditions accordingly.