Back to Terraform

Validation, Checks and Native Terraform Tests

November 5, 2026 Wasil Zafar 28 min read

Choose the right failure mechanism and test behavior without mistaking a valid configuration for correct infrastructure

Table of Contents

  1. What Fmt and Validate Can Actually Prove
  2. Choose a Blocking Condition or an Advisory Check
  3. Structure a Tftest File with Variables and Run Blocks
  4. Test a Module Interface Before Deploying a Full Stack
  5. Tests Can Create Real Resources and Cleanup Can Fail
  6. Build a Passing and Failing Contract Test

What Fmt and Validate Can Actually Prove

The pipeline had been green for three weeks. Formatting passed, validation passed, and the plan for the orders service showed one bucket and one load balancer. The apply stopped ninety seconds later with AccessDenied when it created the bucket: the credentials could read the account but had never been granted the write.

terraform fmt is a formatter, not a checker. It parses enough to understand blocks, then rewrites layout: two-space indentation, aligned =, one argument per line. The check flag changes nothing and exits non-zero when a file would change; the diff flag prints the patch. A file can be perfectly formatted and still reference a missing resource type or pass the wrong argument name.

terraform validate goes further than layout. It parses every file, resolves references, evaluates known types, and checks each argument against the provider schema installed by init. It catches the misspelled argument, the missing required attribute, the wrong type, the renamed reference, the unmarked sensitive output. It answers one question: would this configuration get past parsing and schema checking?

The gaps are where incidents live.

  • Credentials. Validation never authenticates. Read and write are separate grants, so a plan can succeed and the first create can fail.
  • Names. S3 bucket names are global; load balancer and IAM role names are per account; DNS records are per zone. No schema contains those namespaces.
  • Quota and capacity. vCPU limits, elastic IP limits, regional availability and account blocks are runtime facts. A plan reserves nothing.
  • Behaviour. A valid bucket can have the wrong policy, a valid load balancer can route to an empty target group, a valid deployment can return 500s.

Think of proofreading a recipe. Spell-check and layout catch a missing ingredient line. They cannot tell you whether the oven reaches 200°C, whether the shop has the fish, or whether the sauce splits. Formatting is layout, validation is the ingredient list and units, planning is the shopping trip, and applying is the cooking. Only a check or a test tastes the result.

Figure 1 follows the four gates and the claim each can honestly make. Figure 2 shows the same idea as layers, with what stays invisible to each one printed beside it.

What Fmt and Validate Can Actually Prove
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    SRC["Configuration and variable values"] --> FMT["terraform fmt -check"]
    FMT -->|"passes"| FMT1["Layout is canonical"]
    FMT -->|"differs"| FMT2["CI fails on formatting only"]
    SRC --> VAL["terraform validate"]
    VAL -->|"passes"| VAL1["Syntax, references and
provider schema agree"] VAL -->|"bad argument, type
or reference"| VAL2["Error before a plan exists"] VAL1 --> PLAN["terraform plan"] PLAN -->|"provider read succeeds"| PLAN1["Change set is plausible;
write permissions untested"] PLAN -->|"refresh denied,
data source fails"| PLAN2["Error while reading"] PLAN1 --> APPLY["terraform apply"] APPLY -->|"API accepts every call"| OK["Objects recorded in state"] APPLY -->|"quota, IAM write,
duplicate name, capacity"| BAD["Error after partial change"] OK --> RUN["Running service"] RUN -->|"health, latency,
correct response"| HEALTH["Only a check or a test
can observe this"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class SRC,PLAN,APPLY primary; class FMT,VAL secondary; class FMT1,VAL1,PLAN1,OK,HEALTH ok; class FMT2,VAL2,PLAN2,BAD danger; class RUN warn;
Four checkpoints and the claims each one can make Formatting sees layout, validation sees syntax and provider schema, planning sees provider reads and a proposed change set, and apply sees the API accept writes. Each band names what stays invisible to that checkpoint, and a crimson strip records the failures that only apply reveals. A pass moves you to the next gate, not to working infrastructure fmt: layout canonical spacing, alignment, block shape validate: configuration and schema references resolve, arguments and types match plan: proposed change set provider reads, unknowns, replacement markers apply: API accepted the writes objects recorded in state cannot see meaning, unknown arguments, bad types credentials, IAM write grants, quota, name collisions, regional capacity, variable rules that need real values apply-only permissions, race conditions, eventual consistency, cost, whether the service will answer a request latency, correctness, health, policy drift after the run, behaviour under load The green pipeline in the incident proved layout and schema. The first API write discovered the missing permission. A check or a test would have found it earlier.

Place the commands, don't distrust them

Each command earns a different claim. Run the formatter check so diffs stay readable, and validation so the module stays self-consistent. Neither one is a deployment test: the first honest test of provider behaviour asks a provider to act, then asks whether the result matches the contract.

Choose a Blocking Condition or an Advisory Check

A rule has two properties that matter more than its syntax: when the value can be evaluated, and what should happen when the rule is false. Five mechanisms exist because those answers differ, and choosing wrongly yields either a pipeline that cannot deploy or an incident nobody was paged for.

Input variable validation runs before a plan and sees only its own variable, through var.<name>. That makes it the place for format and range rules: a name pattern, a tier from a fixed list, a whole-number replica count. Failure stops the operation before any provider call.

Preconditions belong to a resource, data source or output and check an assumption that block depends on. They may read other objects, including data sources, so they can ask whether a VPC has two private subnets. Known values are checked while planning; unknown values defer the check to apply, where it still stops that object's action.

Postconditions assert a guarantee about the result. They are evaluated after the change is planned and applied, may use self, and block anything that depends on the object without undoing it. A failed postcondition leaves the new bucket in state and stops the resources that would have used it.

check blocks run last and warn instead of erroring. That is a different instrument, not a weaker one: a check can hold a nested data source that reads a live endpoint, so it answers "is the service healthy now?" rather than "are the arguments declared correctly?". It is also what HCP Terraform can run continuously.

Test assertions block in a different place. An assertion in a .tftest.hcl file fails the test run, and therefore CI, but never runs in a production apply and never rolls anything back.

The mapping follows from where the value becomes knowable: caller value before planning is validation, this change before it starts is a precondition, the result before dependants use it is a postcondition, an operator without stopping deployment is a check, and the next pull request is a test.

Advisory in production, blocking in CI

A failing check still fails a test run unless the test expects it, so a rule that only warns in production blocks a pull request by default. The reverse mistake is expecting the failure attribute to absorb any error: it covers custom conditions only, on the object you name.

Messages deserve the same care as conditions. Terraform already prints the file, line and expression values, so explain why the rule exists and what a good value looks like. "Invalid tier" teaches nothing; naming the three allowed values tells the caller which decision they are making.

Table 1 compares the mechanisms on the axes that decide the choice.

MechanismWhen it blocksWhat it can proveWhat it cannot prove
terraform fmt -checkCI, when a file would changeLayout is canonical and the file parsesArguments, types, references, behaviour
terraform validateBefore a plan, after initReferences resolve; arguments and types match the providerCredentials, permissions, quota, names, runtime behaviour
Variable validationBefore the plan is builtThe caller's value satisfies rules on that variable aloneOther objects, data sources, apply-time values
preconditionDuring planning, or during apply when unknownAn assumption about this object or its dependencies holdsWhether the provider produces the promised result
postconditionAfter the change is planned and appliedThe object satisfies a guarantee about selfIt cannot undo the object; it only stops dependants
check blockNever; it warns at the end of plan or applyThat a live or computed assertion failedAnything blocking, reverting, or preventing the change
Test assertA terraform test run, and CI when requiredThe contract held in a controlled runDrift, load behaviour, anything not exercised

Figure 3 draws the decision with its failure branches. The left side stops work; the right side records a verdict and lets the operation finish.

Choose a Blocking Condition or an Advisory Check
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    RULE["A rule you want to enforce"] --> WHEN{"When is the value
knowable?"} WHEN -->|"caller's own value,
before planning"| VAR["variable validation"] WHEN -->|"assumption about
other objects"| PRE["precondition"] WHEN -->|"result of this object"| POST["postcondition"] WHEN -->|"only at the end,
including live probes"| CHK["check block"] VAR -->|"false"| STOP["Error: no plan is produced"] PRE -->|"false while planning"| STOP PRE -->|"false during apply"| STOPOBJ["Error: this object's
planned action stops"] POST -->|"false"| STOPDOWN["Error: dependants stop,
created object remains"] CHK -->|"false"| WARN["Warning: operation completes"] WARN --> ALERT["CI alert, dashboard,
or continuous validation"] VAR --> TEST["terraform test fails"] PRE --> TEST POST --> TEST CHK --> TESTEXP["test fails unless the run
declares expect_failures"] TEST --> GATE["Pull request is blocked"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class RULE,WHEN primary; class VAR,PRE,POST,CHK secondary; class STOP,STOPOBJ,STOPDOWN,GATE danger; class WARN,ALERT,TESTEXP warn; class TEST ok;

Authority also decides blast radius. Validation rejects a bad call; a precondition stops one object while independent objects continue; a postcondition fails after the object exists; a check fails after everything is spent. Moving a rule earlier makes failure cheaper but narrows what it can see.

Structure a Tftest File with Variables and Run Blocks

A test file is not a shell script around a plan. It is a small HCL program with its own schema, run by the same core. Terraform discovers test files under tests/ beneath the module, and also loads any in the module directory. Each file is a suite; each run block is one plan or apply with its own assertions.

A file has four optional parts: a test block, run blocks, a file-level variables block, and provider blocks. File-level variables reach every run. A run's own variables block replaces them, and replacement is whole-value: overriding an object means restating every attribute it needs.

Committed test values win

Test-file variables outrank the environment. They beat the TF_VAR prefix, the automatic variable file and the command-line var flag, so CI cannot override a committed value. That is good for determinism and bad if an account-specific name is committed. Automatic variable files inside the test directory apply only there, which is the supported place for credentials and account IDs.

The default command is the most consequential choice in the file. Omitted, it means apply, so a run with no command creates real infrastructure. Set it to plan for names, tags, counts and expressions known before creation. Reserve apply for provider-assigned values such as a generated bucket name or an ARN.

Assertions pair a condition with an error message. Conditions can reference resources and data sources, the current run's outputs, and earlier runs' outputs by name, which passes a generated value between runs without parsing the CLI output.

expect_failures names the objects whose failure the run expects. It accepts variables, resources, data sources, outputs and check blocks, and the test passes only when the named object reports a custom-condition failure. A type error is not an expected failure. Every condition except a check halts execution, so a run can reliably expect one failing object and must assert only values computed before it fails. Prefer plan: with apply, a failure during planning aborts before apply and the test reports a failure even though it was expected.

State is the other structural idea. Each file keeps state in memory, starting empty and separate from your real state. Runs using the same module share one state; runs loading an alternate module get another, and a state key forces sharing. At the end, Terraform destroys what it created in reverse run order, which is why a setup bucket is destroyed after the run that filled it.

Table 2 collects the controls that decide what a file does and what a run costs.

ControlDefaultUse it to
commandapplyKeep plan suites read-only; use apply only for provider-assigned values
run variablesinherit file valuesOverride one run, restating the whole object
expect_failuresnoneAssert that a named variable, resource, output or check fails
-filterwhole test directoryRun one suite, such as plans on every pull request
-verboseconcise outputShow the plan or state behind a failed assertion
-jsonhuman-readable outputWrite per-run status for a CI parser
-junit-xmlhuman-readable outputWrite a report most CI systems already display
-test-directorytests/Load suites from another directory

The widget puts the pieces together: one module, a plan suite with two negative cases, and an apply suite that checks provider-assigned values. They are separate files because -filter selects files, not run blocks, so a pull request can run plans without creating anything.

# modules/service/main.tf
terraform {
  required_version = ">= 1.9.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

variable "service" {
  description = "One service's identity, tier and ownership tags."
  nullable    = false

  type = object({
    name = string
    tier = string
    tags = map(string)
  })

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{2,20}$", var.service.name))
    error_message = "service.name must be 3 to 21 lowercase letters, digits or hyphens, starting with a letter."
  }

  validation {
    condition     = contains(["bronze", "silver", "gold"], var.service.tier)
    error_message = "service.tier must be bronze, silver or gold. Use silver for internal services and gold for customer-facing ones."
  }
}

locals {
  bucket_prefix = "${var.service.name}-${var.service.tier}-"
}

resource "aws_s3_bucket" "artifacts" {
  bucket_prefix = local.bucket_prefix
  force_destroy = true

  tags = merge(var.service.tags, {
    managed-by = "terraform"
    tier       = var.service.tier
  })
}

resource "aws_s3_bucket_versioning" "artifacts" {
  bucket = aws_s3_bucket.artifacts.id

  versioning_configuration {
    status = "Enabled"
  }
}

output "bucket" {
  description = "Generated bucket name, including the provider's random suffix."
  value       = aws_s3_bucket.artifacts.bucket
}

output "bucket_arn" {
  description = "ARN of the artifact bucket, for bucket policies in the parent module."
  value       = aws_s3_bucket.artifacts.arn
}

# modules/service/tests/plan.tftest.hcl
variables {
  service = {
    name = "orders-api"
    tier = "gold"
    tags = { owner = "payments" }
  }
}

run "plan_derives_the_contract" {
  command = plan

  assert {
    condition     = aws_s3_bucket.artifacts.bucket_prefix == "orders-api-gold-"
    error_message = "bucket_prefix must be <name>-<tier>- so operators can find the bucket from the service record."
  }

  assert {
    condition     = aws_s3_bucket.artifacts.tags["tier"] == "gold"
    error_message = "The tier tag must be copied from service.tier; cost reports filter on it."
  }
}

run "plan_rejects_an_invalid_name" {
  command = plan

  variables {
    service = {
      name = "Orders_API"
      tier = "gold"
      tags = {}
    }
  }

  expect_failures = [var.service]
}

run "plan_rejects_an_unknown_tier" {
  command = plan

  variables {
    service = {
      name = "orders-api"
      tier = "platinum"
      tags = {}
    }
  }

  expect_failures = [var.service]
}

# modules/service/tests/apply.tftest.hcl
variables {
  service = {
    name = "orders-api"
    tier = "gold"
    tags = { owner = "payments" }
  }
}

run "apply_creates_a_versioned_bucket" {
  command = apply

  assert {
    condition     = startswith(output.bucket, "orders-api-gold-")
    error_message = "The created bucket lost the contract prefix; check local.bucket_prefix."
  }

  assert {
    condition     = output.bucket_arn != ""
    error_message = "The module must publish an ARN; the parent module uses it in a bucket policy."
  }

  assert {
    condition     = aws_s3_bucket.artifacts.force_destroy
    error_message = "Test buckets must set force_destroy so cleanup can delete objects and versions."
  }
}
cd modules/service

# Install the provider schema that validate checks against.
terraform init -input=false

# Layout and schema gates. Neither one contacts AWS.
terraform fmt -check -recursive -diff
terraform validate

# Plan suite: no objects created, safe on every pull request.
terraform test -filter=tests/plan.tftest.hcl

# Apply suite: creates and destroys a real bucket. Use test credentials.
terraform test -filter=tests/apply.tftest.hcl -verbose

# Machine-readable results for the pipeline.
terraform test -filter=tests/apply.tftest.hcl -json > test-results.json

Reading the output is part of the skill. Verbose mode prints the plan or state for each run, so a failed assertion shows the unknown value instead of leaving you to guess. The JSON and JUnit flags write machine-readable results for a pipeline.

What the file does not choose is the account. Test files may declare provider blocks and aliases that read variables and earlier outputs, which is how a setup run can mint short-lived credentials. Without one, Terraform uses the normal provider configuration and environment, including whatever account your shell or CI role is using. Convenient locally, dangerous in a pipeline that also deploys production.

Test a Module Interface Before Deploying a Full Stack

A module interface is smaller than a stack and larger than a resource. It consists of inputs a caller must supply, outputs a caller may consume, defaults that fill omissions, and failures a caller can expect. Those four things are the contract, and a native test can exercise them without standing up the network, cluster and DNS a full environment needs.

Test at the boundary for three reasons. The run is fast because it creates one or two objects instead of a stack. The failure names the module rather than a root configuration fifty resources away. And the assertions become documentation: a new caller reads the test file and sees which output is stable, which value is derived, and which input is rejected.

Good assertions share a shape. Assert the output a caller consumes, not the internal resource that happens to produce it. Assert naming conventions and the tags that cost reports and policies depend on. Assert that defaults apply when an optional attribute is omitted. Assert the shape of a computed value without pinning a provider's random suffix: startswith(output.bucket, "orders-api-gold-") is a contract; an exact 42-character name is a snapshot that breaks for no reason.

Avoid values that are not promises. An exact availability zone, a provider-assigned numeric ID, a timestamp, or the order of a set are implementation details. They make the suite flaky and teach reviewers to ignore failures.

Negative cases earn their keep, and need the same discipline. Every validation deserves at least one expect_failures run, because a rule with no test can be deleted in a refactor unnoticed. Test boundaries, not just an obviously wrong value: shortest and longest allowed name, missing optional attribute, the empty list a length() rule should reject. Test one failing object per run; if two rules could fail on one input, split the input so the failure identifies the rule.

Module tests also catch composition defects a resource test cannot. A module that promises an ARN but exports only a name produces a reference error in the parent; a test that asserts the output turns that into a module-level failure. A module that silently drops a tag passes its own resource assertions and fails the caller's cost allocation. One run can pass an earlier run's bucket name into a later run that reads it through a data source, proving the output is usable rather than merely present.

Mocking changes what a test can claim. Since Terraform 1.7, a mock provider and mock resources let a plan proceed without credentials by inventing provider responses. That is excellent for naming logic, conditionals and wiring on every commit. It is not evidence that the provider accepts the arguments, that IAM allows the call, or that the created object has the promised shape.

# modules/service/tests/interface.tftest.hcl
mock_provider "aws" {
  mock_resource "aws_s3_bucket" {
    defaults = {
      bucket = "mock-orders-api-gold-00000000"
      arn    = "arn:aws:s3:::mock-orders-api-gold-00000000"
    }
  }
}

variables {
  service = {
    name = "orders-api"
    tier = "gold"
    tags = { owner = "payments" }
  }
}

run "plan_derives_the_contract_without_credentials" {
  command = plan

  assert {
    condition     = aws_s3_bucket.artifacts.bucket_prefix == "orders-api-gold-"
    error_message = "bucket_prefix must be <name>-<tier>- so operators can find the bucket from the service record."
  }

  assert {
    condition     = aws_s3_bucket.artifacts.tags["tier"] == "gold"
    error_message = "The tier tag must be copied from service.tier; cost reports filter on it."
  }
}
cd modules/service

# No credentials, no API calls: only naming, tags and wiring are exercised.
terraform test -filter=tests/interface.tftest.hcl

# The apply suite is the evidence that AWS accepts the calls.
terraform test -filter=tests/apply.tftest.hcl -verbose

A mock is not evidence

A mock-backed suite and an apply-backed suite answer different questions. The mock proves the module's logic on every commit; only the apply run proves the provider accepts the arguments and IAM allows the call. A module with only the first has not been tested against reality.

Tests Can Create Real Resources and Cleanup Can Fail

The default is apply

Native tests can create real infrastructure that costs money. A developer who writes three runs to check a naming convention, forgets to set the plan command, and runs against a sandbox account gets three objects, three sets of API calls, and a cleanup path that must succeed for the account to stay clean.

Test state is in memory, but the objects are not. Terraform starts each file with an empty state, keeps it in the process, and never writes it to your configured backend. That isolation makes tests safe for existing infrastructure: a test cannot adopt, modify or destroy objects your real state owns. It also means there is no state file after the process exits. If cleanup fails, the leftovers are unmanaged, and terraform state list will not mention them.

Four boundaries decide whether a test run is safe. Credentials, naming, teardown order and parallelism each fail in a different way, and Table 3 maps each one to its control.

BoundaryHow it failsControl
CredentialsThe run inherits the shell or CI identity, so a test can touch productionDedicated test account, short-lived federation, role scoped to the resource types, region pinned, secrets in CI or automatic variable files
NamingA fixed name collides with a previous failed run, a parallel job or a manual experimentProvider prefix where it exists, run-scoped suffix where it does not, tags with run id and expiry
Teardown orderReverse run order is broken by deletion protection, object lock, retention, a non-empty bucket or a KMS key awaiting deletionforce_destroy on test buckets, no prevent_destroy, short retention
ParallelismTwo runs race for the same name or exhaust a quota that looked generous in isolationKeep parallel off for shared names, cap it with -run-parallelism, treat speed as the only benefit

Teardown follows reverse run order. A setup bucket is destroyed after the run that wrote objects into it, and within a state the graph decides. A resource that protects itself turns a passing test into a cleanup failure after every assertion succeeded. Mind length limits too: an S3 bucket name is at most 63 characters and its prefix at most 37, so a long service name plus tier plus suffix can fail before it reaches the API.

Figure 4 follows the lifecycle and the branch that matters: assertions pass and cleanup fails. The lower branch is the state to plan for, because it leaves objects Terraform no longer knows about.

A test run can pass and still leave infrastructure behind Plan runs create nothing. An apply run creates real objects while test state stays in memory. Assertions then pass or fail, and cleanup is attempted. On success the objects are destroyed and the state is discarded. On failure the process exits, the state disappears, and the objects remain unmanaged, so a tag-based inventory is the only way to find them. One test file, two possible endings In-memory test state plan runs: nothing created apply run creates objects real API calls, real cost assertions read outputs and resource attributes pass or fail the run then destroy succeeds objects removed state discarded account is clean destroy fails or the run is interrupted Residual objects, no state file Terraform reports what it could not destroy, then exits. In-memory state disappears with the process, so the next run cannot adopt or delete those objects without an import or an external inventory. Tag every test object run id, owner, expires-at prefix carries the service name Scheduled sweep and verification list by tag, delete expired objects alert on any object past its expiry

Cleanup failure is not rare enough to treat as an edge case. A bucket with objects and no force_destroy, a load balancer with deletion protection, a database with a final snapshot, or a CI job cancelled at the wrong moment all produce it. Terraform prints diagnostics and a list of resources it created but could not destroy; that list is a starting point for manual cleanup, not proof it is complete. An interrupted process may print nothing at all.

The durable answer is an inventory outside Terraform. Tag every test object with the repository, run identifier and an expiry. Give the test account a scheduled job that lists resources by those tags and deletes anything past expiry, plus a check that alerts when the count does not return to zero after a run. A test that cannot be cleaned automatically should not be allowed to create anything.

Build a Passing and Failing Contract Test

The exercise takes the module from the first widget and breaks it three ways: a positive assertion, a negative test that loses its expected failure, and a cleanup path that cannot finish. All three are defects a reviewer could miss in a diff, and all three produce a failure that names the contract rather than a provider error.

Lab

Test the service contract

Execution status: design-only. Terraform CLI 1.17.1 and AWS provider 6.72.0 were current on 5 November 2026. The ordering follows documented test-framework behaviour; no AWS apply was performed for this article.

Prerequisites. Terraform CLI 1.17.1, a disposable AWS account and region, credentials that can create and delete S3 buckets, and permission to list buckets. Use a prefix containing your initials or a run identifier if the account is shared. Create three files exactly as in the first widget:

  • Module: modules/service/main.tf
  • Plan suite: tests/plan.tftest.hcl
  • Apply suite: tests/apply.tftest.hcl
  1. From modules/service, run terraform init -input=false. The AWS provider downloads, giving validate a schema to check.
  2. Run terraform fmt -check -recursive -diff and terraform validate. Both pass. In a scratch copy, rename the bucket_prefix argument to bucket_name and validate again: the error names the unsupported argument, which is the schema layer working.
  3. Run terraform test -filter=tests/plan.tftest.hcl. Expect three runs to pass: one positive plan and two expected validation failures. No bucket exists, so this suite is safe on every commit.
  4. Run terraform test -filter=tests/apply.tftest.hcl -verbose. Expect one apply to create a bucket, satisfy three assertions, and destroy the bucket at the end. Verbose output shows the unknown name at plan time and the concrete name in the apply state.
  5. Break the prefix: change the middle separator in local.bucket_prefix from - to _. Rerun the plan suite. Expect plan_derives_the_contract to fail with the file, line, run name and actual prefix. S3 rejects underscores, so the apply suite could not succeed either; the plan assertion is the cheaper signal.
  6. Restore it. Delete the tier validation block and rerun the plan suite. Expect plan_rejects_an_unknown_tier to fail because the expected failure never occurred. The rule disappeared and the test noticed.
  7. Restore the validation. Add lifecycle { prevent_destroy = true } to the bucket and rerun the apply suite. Assertions pass, then cleanup cannot destroy the bucket. Terraform reports the resources it created but could not destroy and exits non-zero.
  8. Remove prevent_destroy, rerun the apply suite, and confirm cleanup succeeds. If the earlier run left a bucket, delete it manually and note that the new run could not see it.

Expected observation. A positive failure names the run, condition and actual value, localizing the defect without reading a plan. A missing validation makes the negative run fail in the opposite direction: an error was expected and success arrived. Cleanup failure is the only one that happens after every assertion passed, and it leaves no state for the next run to repair.

Failure checks. Each symptom points at one layer:

  • Plan suite creates a bucket: command = plan is missing or misspelled.
  • A negative run passes on an invalid value: the rule is missing, or the named object is wrong.
  • Apply suite passes but a bucket remains: check force_destroy, any leftover prevent_destroy, or an interrupted destroy.
  • Files are not found: confirm you are in the module directory and the names end in .tftest.hcl.

Cost dimensions. One versioned S3 bucket for the duration of the apply suite plus a handful of requests. An empty bucket is effectively free, but versioned objects and incomplete multipart uploads can persist charges if cleanup fails. Plan suites cost nothing beyond provider initialization.

Cleanup. Delete any bucket from a failed run, confirm none matches the test prefix, and remove test-results.json and saved plans. Keep the test account's inventory check running: a green test is not proof of an empty account.

Before writing a rule, run a short checklist. Decide whether the value is knowable before planning, during planning, or only after apply. Decide whether a false result should stop a change, stop a dependant, or page someone. Put the rule in the earliest mechanism that can see the value and has the authority you need. Then write the test that proves the rule fires, including the case where it should and the case where it should not.

A green pipeline proves three narrow claims. Running formatting, validation, plan tests and a small apply suite does not prove the infrastructure is correct. It proves the configuration is well formed, the interface behaves as documented, and the provider accepts the calls the module makes. Those are three different claims, and keeping them separate is what stops a green check mark from being mistaken for a working service.

Next in the Series

In Linting, Security Scanning and Policy Tests in CI, we'll explore Combine fast static checks with plan-aware policy decisions and useful diagnostics.