Skip to main content

Infrastructure as code · Intermediate · 22 min

Catch mistakes early with Terraform validation, preconditions and check blocks

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · hashicorp/local 2.9 · hashicorp/http 3.6 · Python 3

You will add variable validation, preconditions, postconditions and a check block to a small Terraform configuration, break each one on purpose and read the message it gives.

On this page

Most Terraform mistakes are not syntax errors. They are a typo in an environment name, a port that needs root, a production deploy with one replica, or a release string someone pasted with a trailing word. terraform validate accepts all of them, because they are valid HCL. You find out when something breaks after the apply.

Terraform gives you three places to stop these earlier, and each one runs at a different moment:

  • Variable validation rejects a bad input before Terraform plans anything.
  • Preconditions and postconditions sit on a resource or data source. A precondition checks the assumptions a resource depends on; a postcondition checks what came out. Both stop the run with an error.
  • Check blocks look at the running system after apply, for example by calling a health endpoint. A failed check is a warning, not an error, so it tells you something is wrong without blocking the change.

In this tutorial you build a small configuration that writes an app's settings file from a RELEASE file and a few variables, then add each kind of check, break it on purpose and read the message. A short Python script plays the deployed app, so you need no cloud account and nothing bills. The demo lives in ~/checks-demo.

Step 1 · Install Terraform 1.17 and Python

Install curl, unzip and Python 3, then download Terraform 1.17.2 for your machine's architecture, check it against HashiCorp's published checksums and put it on your PATH:

Bash
sudo apt update
sudo apt install -y curl unzip ca-certificates python3
TF_VERSION=1.17.2
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "terraform_${TF_VERSION}_SHA256SUMS"
unzip -o "terraform_${TF_VERSION}_linux_${ARCH}.zip" terraform
sudo install -m 0755 terraform /usr/local/bin/terraform
terraform version
python3 --version

A binary installed this way gets no updates from apt. To upgrade, run the same commands with a newer TF_VERSION.

Providers are downloaded on every terraform init unless you keep a cache. On metered or prepaid data, set one up now so each provider is fetched once per machine:

Bash
mkdir -p ~/.terraform.d/plugin-cache
echo 'export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"' >> ~/.bashrc
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

Check it worked

sha256sum prints a line ending in OK, terraform version prints Terraform v1.17.2 on its first line, and python3 --version prints Python 3. followed by a version number.

Step 2 · Build the starting configuration

The configuration reads the release to deploy from a file called RELEASE and writes site/app.env, the settings file the app would load. Create the project:

Bash
mkdir -p ~/checks-demo/site
cd ~/checks-demo
echo "v1.4.0" > RELEASE

cat > versions.tf <<'HCL'
terraform {
  required_version = "~> 1.17.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
    http = {
      source  = "hashicorp/http"
      version = "~> 3.6"
    }
  }
}
HCL

cat > variables.tf <<'HCL'
variable "environment" {
  description = "Where this copy runs: dev, staging or prod."
  type        = string
  default     = "dev"
}

variable "port" {
  description = "Port the app listens on."
  type        = number
  default     = 8085
}

variable "replicas" {
  description = "How many copies of the app to run."
  type        = number
  default     = 1
}

variable "settings" {
  description = "Extra KEY=value lines for app.env."
  type        = map(string)
  default     = { LOG_LEVEL = "info" }
}
HCL

cat > main.tf <<'HCL'
data "local_file" "release" {
  filename = "${path.module}/RELEASE"
}

locals {
  release = trimspace(data.local_file.release.content)

  settings = merge(var.settings, {
    ENVIRONMENT = var.environment
    PORT        = var.port
    REPLICAS    = var.replicas
    RELEASE     = local.release
  })
}

resource "local_file" "app_config" {
  filename        = "${path.module}/site/app.env"
  file_permission = "0644"
  content         = join("", [for key, value in local.settings : "${key}=${value}\n"])
}
HCL

terraform init
terraform plan -out=tfplan
terraform apply tfplan
cat site/app.env

The http provider is not used yet. Declaring it now means one init covers the whole tutorial.

Nothing here stops a bad value. Try a few before you add any checks:

Bash
terraform plan -var environment=production -var port=80

Terraform plans the change without complaint: it would write ENVIRONMENT=production and PORT=80 into the file. Do not apply it.

Check it worked

The apply ends with Apply complete! Resources: 1 added, 0 changed, 0 destroyed. cat site/app.env prints five lines in key order: ENVIRONMENT=dev, LOG_LEVEL=info, PORT=8085, RELEASE=v1.4.0 and REPLICAS=1. The plan with production and port 80 shows 1 to add, 0 to change, 1 to destroy and no error.

Step 3 · Reject bad inputs with validation blocks

A validation block belongs to a variable. Its condition must be true for the value to be accepted, and its error_message is what the person running Terraform sees. Write the message for them: say what is allowed and what they passed.

A variable can have several validation blocks, and since Terraform 1.9 a condition can refer to other variables too. That lets replicas depend on environment: one replica is fine for dev, but prod needs two so one can restart while the other serves. Rewrite variables.tf:

Bash
cd ~/checks-demo
cat > variables.tf <<'HCL'
variable "environment" {
  description = "Where this copy runs: dev, staging or prod."
  type        = string
  default     = "dev"

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be one of dev, staging or prod, not \"${var.environment}\"."
  }
}

variable "port" {
  description = "Port the app listens on."
  type        = number
  default     = 8085

  validation {
    condition     = var.port >= 1024 && var.port <= 65535 && floor(var.port) == var.port
    error_message = "port must be a whole number from 1024 to 65535 (got ${var.port}). Ports below 1024 need root."
  }
}

variable "replicas" {
  description = "How many copies of the app to run."
  type        = number
  default     = 1

  validation {
    condition     = var.replicas >= 1 && var.replicas <= 5
    error_message = "replicas must be from 1 to 5 (got ${var.replicas})."
  }

  validation {
    condition     = var.environment != "prod" || var.replicas >= 2
    error_message = "prod needs at least 2 replicas so one can restart while the other serves; you asked for ${var.replicas}."
  }
}

variable "settings" {
  description = "Extra KEY=value lines for app.env."
  type        = map(string)
  default     = { LOG_LEVEL = "info" }
}
HCL

Now break each rule. Run these one at a time and read each error:

Bash
terraform plan -var environment=production
terraform plan -var port=80
terraform plan -var environment=prod

Each one stops with Error: Invalid value for variable, names the file and line of the variable, shows the values involved and prints your message. Nothing is planned, so a typo can never reach the file. The third one is the cross-variable rule: prod is a valid environment, but not with the default single replica. Give it two and the plan goes through:

Bash
terraform plan -var environment=prod -var replicas=2

The condition var.environment != "prod" || var.replicas >= 2 reads as "either this is not prod, or there are at least two replicas". Writing rules as "not this case, or the requirement holds" keeps them short and keeps the other environments unaffected.

Check it worked

The three failing plans print, in turn, environment must be one of dev, staging or prod, not "production"., port must be a whole number from 1024 to 65535 (got 80). and prod needs at least 2 replicas so one can restart while the other serves; you asked for 1. The last plan, with two replicas, shows a plan to replace local_file.app_config and no error.

Step 4 · Check what a resource relies on with a precondition

Some rules are about data Terraform reads, not about a variable. Two apply here. RELEASE must hold one version string, and prod must never run a pre-release such as v1.5.0-rc.1.

The first belongs on the data source that reads the file, as a postcondition: it checks the result of the read, through self. The second belongs on the resource that would carry the bad value into prod, as a precondition: it states what must be true before Terraform creates or changes that resource. Rewrite main.tf with both:

Bash
cd ~/checks-demo
cat > main.tf <<'HCL'
data "local_file" "release" {
  filename = "${path.module}/RELEASE"

  lifecycle {
    postcondition {
      condition     = can(regex("^v[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.]+)?$", trimspace(self.content)))
      error_message = "RELEASE must hold one version such as v1.4.0, but it holds \"${trimspace(self.content)}\"."
    }
  }
}

locals {
  release = trimspace(data.local_file.release.content)

  settings = merge(var.settings, {
    ENVIRONMENT = var.environment
    PORT        = var.port
    REPLICAS    = var.replicas
    RELEASE     = local.release
  })
}

resource "local_file" "app_config" {
  filename        = "${path.module}/site/app.env"
  file_permission = "0644"
  content         = join("", [for key, value in local.settings : "${key}=${value}\n"])

  lifecycle {
    precondition {
      condition     = var.environment != "prod" || !strcontains(local.release, "-")
      error_message = "prod only runs final releases; ${local.release} is a pre-release. Ship it to staging first."
    }
  }
}
HCL

Break the release file, then put a pre-release in it and aim at prod:

Bash
echo "1.5" > RELEASE
terraform plan

echo "v1.5.0-rc.1" > RELEASE
terraform plan -var environment=prod -var replicas=2
terraform plan -var environment=staging

The first plan fails with Error: Resource postcondition failed. Terraform shows the content it read, self.content is "1.5\n", so you can see the problem without opening the file. The second fails with Error: Resource precondition failed and lists both values the condition used, local.release and var.environment. The staging plan succeeds, because the precondition only guards prod.

You could have written the pre-release rule as a second validation on environment, since validations can read data sources since Terraform 1.9. Putting it on the resource keeps the rule next to the thing it protects, and the error points at that resource. Put the release back before you go on:

Bash
echo "v1.4.0" > RELEASE
terraform plan -var environment=prod -var replicas=2

Check it worked

You saw both errors, each with the values that caused it, and the final plan with v1.4.0 in prod runs without an error. cat RELEASE prints v1.4.0.

Step 5 · Guarantee the output with a postcondition

A postcondition on a resource checks what the resource ended up as, whatever fed into it. Here the guarantee is that every line of app.env is KEY=value with an upper-case key and a non-empty value, because the app's loader would skip or choke on anything else. The keys come partly from var.settings, which anyone can pass, so checking the finished content catches every source at once.

Add a postcondition next to the precondition. Rewrite the resource at the end of main.tf by writing the whole file again:

Bash
cd ~/checks-demo
cat > main.tf <<'HCL'
data "local_file" "release" {
  filename = "${path.module}/RELEASE"

  lifecycle {
    postcondition {
      condition     = can(regex("^v[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.]+)?$", trimspace(self.content)))
      error_message = "RELEASE must hold one version such as v1.4.0, but it holds \"${trimspace(self.content)}\"."
    }
  }
}

locals {
  release = trimspace(data.local_file.release.content)

  settings = merge(var.settings, {
    ENVIRONMENT = var.environment
    PORT        = var.port
    REPLICAS    = var.replicas
    RELEASE     = local.release
  })
}

resource "local_file" "app_config" {
  filename        = "${path.module}/site/app.env"
  file_permission = "0644"
  content         = join("", [for key, value in local.settings : "${key}=${value}\n"])

  lifecycle {
    precondition {
      condition     = var.environment != "prod" || !strcontains(local.release, "-")
      error_message = "prod only runs final releases; ${local.release} is a pre-release. Ship it to staging first."
    }

    postcondition {
      condition     = alltrue([for line in split("\n", trimspace(self.content)) : can(regex("^[A-Z][A-Z0-9_]*=\\S", line))])
      error_message = "Every line in app.env must be KEY=value with an upper-case key and a value. Check the keys and values in var.settings."
    }
  }
}
HCL

Pass a setting with a lower-case key, then one with an empty value:

Bash
terraform plan -var 'settings={"log level"="debug"}'
terraform plan -var 'settings={LOG_LEVEL=""}'

Both fail with Error: Resource postcondition failed, and Terraform prints self.content so you can spot the bad line. These fail at plan time because the content is already known from your configuration. Terraform checks a postcondition as soon as the values it uses are known; a condition on something only the provider learns, such as an ID a cloud API assigns, is checked after apply instead, and the apply then stops with the error.

Now apply a good set of settings so the file on disk matches the code:

Bash
terraform plan -out=tfplan -var 'settings={LOG_LEVEL="debug"}'
terraform apply tfplan
cat site/app.env

You will pass settings again in later commands only if you want to keep debug; the steps below use the default, info.

Check it worked

Both bad plans end with Every line in app.env must be KEY=value with an upper-case key and a value. The apply ends with Apply complete! Resources: 1 added, 0 changed, 1 destroyed. (the local provider replaces a file when its content changes), and cat site/app.env shows LOG_LEVEL=debug.

Step 6 · Watch the running app with a check block

Everything so far checks Terraform's own inputs and outputs. It cannot tell you whether the app is up, or whether it is still running last week's build. A check block can. It has its own data source, scoped to the block, and one or more assert blocks. Terraform runs it at the end of every plan and apply, and a failure is printed as a warning: the run still succeeds, and the warning tells you to look.

First, the app. This Python script answers GET /health with ok and the release it was started with, which is the kind of endpoint a real service exposes. Save it as app.py:

Bash
cd ~/checks-demo
cat > app.py <<'PY'
"""A stand-in web app that reports its release on /health."""
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

RELEASE = sys.argv[1]
PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 8085


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/health":
            status, body = 200, f"ok {RELEASE}\n"
        else:
            status, body = 404, "not found\n"
        data = body.encode()
        self.send_response(status)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)


print(f"Serving release {RELEASE} on http://127.0.0.1:{PORT}/health", flush=True)
HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
PY

Then the check, in a file of its own. It asserts two things: the endpoint answers 200, and the body names the release in RELEASE:

Bash
cat > checks.tf <<'HCL'
check "app_health" {
  data "http" "health" {
    url = "http://127.0.0.1:${var.port}/health"
  }

  assert {
    condition     = data.http.health.status_code == 200
    error_message = "GET /health returned ${data.http.health.status_code}, not 200."
  }

  assert {
    condition     = strcontains(data.http.health.response_body, local.release)
    error_message = "/health does not report release ${local.release}; the app may be running an old build."
  }
}
HCL
terraform plan -out=tfplan
terraform apply tfplan

The app is not running yet, so the request fails. Terraform prints Warning: Error making request with connection refused, and still finishes the apply, which puts LOG_LEVEL=info back in app.env. That is the point of a check: the change you asked for is made, and you are told the system around it is not healthy.

In your second terminal, start the app at the release Terraform expects. It keeps running until you press Ctrl+C:

Bash
cd ~/checks-demo
python3 app.py v1.4.0

Back in the first terminal, plan again:

Bash
cd ~/checks-demo
curl -s http://127.0.0.1:8085/health
terraform plan

The plan lists data.http.health will be read during apply with the note config will be reloaded to verify a check block. Terraform reads a check's data source again on every apply, so this line always appears, and it is not a change to your infrastructure. There are no warnings this time.

Check it worked

The first apply ended with Apply complete! and a connection refused warning. With the app running, curl prints ok v1.4.0, and terraform plan ends with Plan: 0 to add, 0 to change, 0 to destroy. and no Warning: lines.

Step 7 · Ship a release and let the check catch a stale app

Now make the mistake a check block exists for. Bump the release in Terraform, but forget to restart the app:

Bash
cd ~/checks-demo
echo "v1.5.0" > RELEASE
terraform plan -out=tfplan
terraform apply tfplan

The apply writes RELEASE=v1.5.0 into app.env and succeeds. At the end Terraform prints Warning: Check block assertion failed, shows data.http.health.response_body is "ok v1.4.0\n" next to local.release is "v1.5.0", and your message: /health does not report release v1.5.0; the app may be running an old build.

Fix it the way you would in production: restart the app on the new build. In the second terminal, press Ctrl+C, then start it again:

Bash
python3 app.py v1.5.0

Run the plan again in the first terminal:

Bash
terraform plan

Because a check never fails the run, a pipeline that only looks at the exit code will miss it. Make reading the warnings part of your review, or have your pipeline fail when the plan or apply output contains Warning: Check block assertion failed. Keep check URLs to endpoints that answer quickly and need no secrets: they run on every plan, from wherever Terraform runs.

Check it worked

After the restart, curl -s http://127.0.0.1:8085/health prints ok v1.5.0 and terraform plan prints no Warning: lines. Stop the app in the second terminal with Ctrl+C, run terraform plan once more, and the connection refused warning comes back.

Step 8 · Choose the right layer, then clean up

Each kind of check answers a different question. Use this when you decide where a new rule goes:

  • Is this input acceptable on its own, or with the other inputs? Use a validation block on the variable. It fails before planning, and the message names the variable the person typed.
  • Is it safe to create or change this resource with what Terraform has read? Use a precondition on the resource. The rule sits next to what it protects.
  • Did the data source or resource come out the way the rest of the code assumes? Use a postcondition, which can read the result through self.
  • Is the system healthy after the change? Use a check block. It warns and never blocks, so use it for things that can be wrong for reasons outside this configuration.

Whichever you use, the error_message is the part people read in a hurry, often in a CI log on a phone. Say what is allowed, show the value that broke the rule, and say what to do next. If your team works in more than one language, keep messages in the one your runbooks use, and keep them in plain words rather than internal shorthand.

When you are done, destroy what the configuration manages. Read the plan before you apply it:

Bash
cd ~/checks-demo
terraform plan -destroy -out=tfplan
terraform apply tfplan

The next command deletes the whole demo folder, including the state. Check that you are deleting ~/checks-demo and nothing else:

Bash
cd ~
rm -rf ~/checks-demo

If you installed Terraform only for this tutorial, remove the binary and the plugin cache, and delete the TF_PLUGIN_CACHE_DIR line from ~/.bashrc:

Bash
sudo rm -f /usr/local/bin/terraform
rm -rf ~/.terraform.d/plugin-cache

Check it worked

Applying the destroy plan ends with Apply complete! Resources: 0 added, 0 changed, 1 destroyed., and ls ~/checks-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.