Input validation and custom conditions
Start with an input contract
A string type accepts many strings, including names your organization cannot use. A custom validation adds a business rule. The following independent fixture accepts a synthetic service name only if it matches the stated naming policy.
variable "service_name" { type = string default = "catalog-api" nullable = false
validation { condition = can(regex("^[a-z][a-z0-9-]{2,19}$", var.service_name)) error_message = "Use 3 to 20 lowercase letters, digits or hyphens, starting with a letter." }}
output "service_name" { value = var.service_name}The default passes. A name such as Catalog or a fails. regex raises an error when there is no match; can converts that dynamic evaluation error into false. The message describes how to fix the input instead of printing it. With nullable = false and a non-null default, an explicit null selects the default. Do not confuse type constraints with naming policies.
Validate relationships and network inputs
A numeric type alone cannot guarantee an integer count or a capacity limit. This separate fixture compares two inputs. Cross-object references in variable validation require Terraform 1.9 or later; earlier versions can use a resource precondition for this relationship.
variable "capacity" { type = number default = 4 nullable = false}
variable "replicas" { type = number default = 2 nullable = false
validation { condition = var.replicas >= 1 && var.replicas <= var.capacity && floor(var.replicas) == var.replicas error_message = "Replicas must be a positive whole number no greater than capacity." }}
output "replicas" { value = var.replicas}With capacity 4, replicas 4 passes, 5 and 1.5 fail. The boundary is inclusive. Avoid cycles between validation dependencies. A separate example uses a function to recognize IPv4 CIDR syntax.
variable "network" { type = string default = "192.0.2.0/24" nullable = false
validation { condition = can(cidrnetmask(var.network)) error_message = "Provide a parseable IPv4 CIDR prefix." }}
output "netmask" { value = cidrnetmask(var.network)}The default produces 255.255.255.0. A prefix length of 33 fails, and IPv6 is outside this IPv4-specific rule. Parsing is not proof of an allowed address allocation, canonical network address, or lack of overlap. Use an additional allocation policy when necessary.
Check an assumption before a resource operation
When a rule belongs to a particular managed object rather than the module interface, place it next to that object. The next local configuration requires an owner tag.
variable "tags" { type = map(string) default = { owner = "catalog-team" } nullable = false}
resource "terraform_data" "catalog" { input = var.tags
lifecycle { precondition { condition = try(trimspace(var.tags["owner"]) != "", false) error_message = "Set a non-empty owner tag." } }}The default passes; an empty map or whitespace-only owner fails. try handles a missing key or null value that would otherwise cause an evaluation error. This rule protects the catalog record operation, not every operation across the graph. Use a precondition to express what the target needs before it can safely proceed.
Check a result before consumers rely on it
A postcondition belongs to the result-producing block. In this example the consumer depends on a local record output.
variable "label" { type = string default = "catalog-ready" nullable = false}
resource "terraform_data" "catalog" { input = var.label
lifecycle { postcondition { condition = self.output == "catalog-ready" error_message = "The stored label must be catalog-ready." } }}
resource "terraform_data" "consumer" { input = terraform_data.catalog.output}On a fresh run, the default is expected to pass once the output is available. If the stored label is catalog-pending, the postcondition fails when Terraform can evaluate it, preventing dependent changes. Earlier operations may already have completed; this is not a transaction rollback. Some result values are unknown until apply, and a known result may be checked during plan. The fixture is a label assertion, not a real service health test.
Choose the rule by ownership and timing
Use input validation for the caller contract, a precondition for a prerequisite of a target, and a postcondition for a promise about a result. Each false condition can stop progress; none is a complete authorization policy. Keep diagnostics specific, actionable and free of secret values. Practice with the cases worksheet and identify where a failed rule should be reported. All examples are static and expected outcomes are unexecuted.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Input validation and custom conditions — knowledge check
Review input contracts, conditions and check warnings.
Which mechanism best rejects a malformed caller-supplied service name?
Which Terraform version first supports cross-object references in variable validation?
With capacity 4, which value passes the replicas rule?
Where should a rule about the stored output of a resource normally live?
What does a failed postcondition guarantee about prior successful changes?