DevOpsInterviewPrep logo
← 🏗️ Declarative Infrastructure
Foundational

Terraform validation, preconditions and checks: choose what stops a change

Choose input validation, resource preconditions, postconditions and check blocks by failure effect. Run a local warning-versus-error experiment and identify what remains changed after a late failure.

TL;DR: Use a blocking condition for a requirement that must reject the associated change. Terraform check assertions report warnings when false; they are useful observations but do not supply an apply veto. A postcondition evaluated after a change also cannot undo that change.

Decide what failure must do

A team requires a worker pool to have at least two replicas before promotion. The number is a teaching policy, not a universal availability threshold. If the value is a caller input, validate it at that boundary. If the rule depends on the resource's surrounding configuration, place a suitable precondition on the resource that consumes it.

Conditions answer two separate questions: when the necessary values become available, and what happens if the expression is false. HashiCorp's custom-condition guide explains these mechanisms. Values unavailable during planning can defer a condition's evaluation until apply. A preview cannot establish a fact it has not yet observed.

MechanismSuitable claimFailure consequence
Variable validationCaller supplied an allowed inputRejects an invalid input when evaluated
Resource preconditionThis resource may proceed only if its prerequisite holdsBlocks the associated operation
Resource postconditionThe resulting resource meets a required propertyErrors and prevents dependent work; does not roll back prior changes
Check assertionObserve infrastructure health without blocking the operationReports a warning and permits continuation

These controls do not replace access policy. Someone who can edit the validation and execute an unrestricted deployment can remove it. Enforce mandatory organizational rules through the protected deployment path as well as reusable module contracts.

Run an advisory condition locally

Use Terraform 1.5 or later in a new temporary directory. Save this as main.tf. There are no remote resources or external providers; terraform_data uses local state and has no provisioner here.

terraform {
  required_version = ">= 1.5, < 2.0"
}
variable "replicas" {
  type    = number
  default = 1
}
resource "terraform_data" "pool" {
  input = var.replicas
}
check "replica_policy" {
  assert {
    condition     = var.replicas >= 2
    error_message = "This exercise requires at least two replicas."
  }
}

Run terraform init -backend=false and terraform plan. The failed assertion produces a warning, while the plan still proposes the local resource. Inspect the process status too; a pipeline that only checks whether this plan command succeeded will not convert that warning into a rejection.

Now remove the check block and add this inside terraform_data.pool:

  lifecycle {
    precondition {
      condition     = var.replicas >= 2
      error_message = "Refusing a pool smaller than two replicas."
    }
  }

Run terraform plan again. The known input fails the precondition, and the command exits unsuccessfully. terraform plan -var='replicas=2' should pass. This contrast tests enforcement behavior, not simply whether the file contains an assertion. For a rule concerned only with this input's valid domain, variable validation is also an appropriate placement.

Later evidence leaves a recovery obligation

Imagine a resource postcondition checks a provider-returned property that becomes known only after creation. If that condition fails, the remote object can already exist. Independent operations may also have completed. Stop promotion, inspect state and the real system, and decide whether to repair forward or remove the object through a reviewed change.

rendering diagram…

A successful HTTP health check after creation is similarly time-bounded evidence. It does not guarantee future availability. Decide which deployment checks must block promotion, which observations should alert an operator, and which permissions protect the choice from being bypassed. A single boolean named healthy cannot express all those responsibilities.

Test the rejected path and preserve the evidence

For the local fixture, record the command, exit status and whether a plan was produced for each case. Temporarily change the minimum to one. The negative case should now succeed, proving that the original rejection depended on the condition you intended to test. Restore the rule before retaining the fixture.

When a condition is unknown during planning, keep that unresolved status in the review rather than reporting it as passed. If the review process requires a decision before any mutation, obtain the necessary evidence earlier or reject the design. Moving the same expression into a postcondition changes its timing, not the requirement's urgency.

Self-check: an apply ends with a failed check assertion but created the requested object. Did Terraform ignore the check? No. Warning-and-continue is the defined effect. Use the warning-check scenario to practise choosing an enforcement point, then extend the replacement review lesson with a failure-timing decision.

RELATED CONCEPTS
PRACTICE THIS IN REAL QUESTIONS