A condition field is a boolean-valued expression that decides whether Terraform validation succeeds. In a variable validation block, Terraform displays error_message when the expression is false; precondition and postcondition blocks use the same pattern to stop processing when validation fails. section 3.7 section 10.6.1
Use conditions to catch invalid inputs and infrastructure assumptions early. A condition can check length, regular-expression matches, numeric ranges, or integer-ness. Terraform permits multiple conditions in one block, allowing separate checks and messages. section 3.7
The same field behaves differently according to where it is attached:
- Variable validation checks input values. Before Terraform 1.9.0, the expression could access only the variable being validated; Terraform 1.9.0 and later permits related variables when the tested variable is also included. section 3.7
- A precondition runs before a resource is created, while a postcondition runs after a resource or data source is created or updated. section 10.6.1
- Resource conditions can reference other resources and data sources; use self for the resource owning the condition, including each instance created with count or for_each. section 10.6.1
Listing 3.29 Simple validation
variable "description" {
description = "An optional description to apply to resources."
type = string
default = "" #1
validation { #2
condition = length(var.description) <= 125
error_message = "The name can not be longer than 125 characters."
}
}
Inspect a length constraint where length(var.description) <= 125 returns true for acceptable input and error_message explains rejection. section 3.7
Cross-variable resource safeguard
An AWS load balancer precondition can allow dualstack-without-public-ipv4 only when the load balancer type is application. The condition combines two variables and prevents resource creation when the relationship is invalid. Terraform 1.9.0 or later can express the same relationship in variable validation, where the rule is easier to find. section 10.6.1
