Infrastructure inputs can otherwise accept values that cause misconfiguration, outages, security incidents, or failures discovered only after lengthy plan and apply steps. A validation block catches many such errors earlier, inside the variable declaration. section 3.7
A validation block is a subblock of a Terraform variable block. Its condition must evaluate to true or false; Terraform displays error_message when the condition fails. Multiple validation blocks can enforce separate constraints on one variable. section 3.3.1 section 3.7
Restricting a subnet identifier
A module can validate that subnet_id has the format expected by AWS, then pass the accepted value to an aws_instance resource. The condition combines length and regex functions to check the input before resource configuration proceeds. section 3.8.2
Listing 3.30 Multiple validations
variable "my_integer" {
description = "An integer between 0 and 10 inclusive."
type = number
validation { #1
condition = var.my_integer <= 10
error_message = "The value must not be greater than 10."
}
validation { #2
condition = var.my_integer >= 0
error_message = "The value must not be less than 0."
}
validation { #3
condition = can(parseint(tostring(var.my_integer), 10))
error_message = "The value must be an integer."
}
}
Compare separate validations for an inclusive numeric range with a check that the supplied number is an integer. section 3.7
Useful checks include minimum lengths, regular-expression matches, integer tests, and numeric ranges. Before Terraform 1.9.0, a validation condition could access only attributes from its own block; Terraform 1.9 allows broader boolean expressions, provided the tested variable remains included. Error messages must contain at least one sentence beginning with an uppercase letter and ending with a period or question mark. section 3.7
