terraform test: the native testing framework

Intermediate · 28 min

Write .tftest.hcl files with run blocks, assert and expect_failures, know which runs create real infrastructure, and run plan-only tests cheaply.

Before thisFormatting, validation and TFLintInput variables and validation

Ned in the Cloud · 28 min

terraform test: the native testing framework

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Ned in the CloudReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Test files end in .tftest.hcl or .tftest.json and are found in the current directory and tests/ by default.
  • Each run block does a plan or an apply, then checks assert conditions; command = plan creates nothing, and the default, apply, creates real resources and destroys them after the file.
  • expect_failures passes a run only if the listed variable validation, precondition or check fails, which is how error paths are tested.
  • Keep plan tests and apply tests in separate files so CI can run the cheap ones on every pull request.

Passing validate, failing on Friday

A module passes fmt, validate and tflint. It still ships with a bug: a variable validation that rejects a legitimate value, an output that returns the wrong subnet, a count that creates zero load balancers when a flag is false. Static checks read the code. They never run it. Someone finds the bug by applying it to a real environment, which is the expensive way.

For years the answer was a Go test harness that applied real infrastructure (more on that in Terratest). Terraform 1.6 added a native one, terraform test, written in HCL, with no second language. OpenTofu has a tofu test command too.

A test file

Tests live in files ending in .tftest.hcl or .tftest.json. The CLI docs say terraform test searches the current directory and a test directory, which defaults to tests, and -test-directory changes it. Each file is a list of run blocks, executed in order. Each run does a plan or an apply of the configuration and then checks assert blocks.

The shape, from the docs and tutorial:

variables {
  name     = "notes"
  min_size = 2
}

run "name_is_prefixed" {
  command = plan

  assert {
    condition     = aws_lb.this.name == "notes-lb"
    error_message = "load balancer name must be prefixed"
  }
}

run "rejects_zero_instances" {
  command = plan

  variables {
    min_size = 0
  }

  expect_failures = [var.min_size]
}

I wrote this from the documentation and did not run it, because Terraform is not installed here. The docs list what a run block can hold: command (apply, which is the default, or plan), variables, assert, expect_failures, module for a helper module, providers, plan_options (mode, refresh, replace, target), state_key and parallel.

Three parts carry the weight:

  • command = plan checks the plan without creating anything. It is the unit test. It is fast and needs no real resources for anything whose values are known at plan time.
  • command = apply really applies. It is the integration test: it proves the provider accepts what you wrote. The docs warn that terraform test creates real infrastructure, and that after each test file Terraform tries to destroy what it made, in reverse order of the runs, and reports anything it could not remove.
  • expect_failures inverts the test. The run passes only if the listed objects, such as a variable with a validation block, a precondition or a check, fail. This is how you test the error paths, which people forget.

Later runs can read earlier ones. The tutorial shows run.setup_tests.bucket_prefix feeding a variable, and a final run reading run.create_bucket.website_endpoint. The tutorial’s sample output looks like this:

$ terraform test
tests/website.tftest.hcl... pass
  run "setup_tests"... pass
  run "create_bucket"... pass
tests/website.tftest.hcl... tearing down
tests/website.tftest.hcl... pass

Success! 2 passed, 0 failed.

That output is quoted from HashiCorp’s tutorial, not from a run of mine.

Know which runs cost money

The default for command is apply, so a run block with no command line creates real resources. That is a quiet way to get a cloud bill from a test suite. I wrote a small Python script that parses test files, counts the asserts in each run and flags the ones that would apply. It is a stand-in with one heuristic: it treats a run with a providers mapping as mocked, which is an assumption you should check. I ran it on a four-run test file I wrote:

$ python3 -I scan_tests.py tests
web.tftest.hcl
  name_is_prefixed         command=plan            asserts=1 expect_failures=False creates real infra? no
  rejects_zero_instances   command=plan            asserts=0 expect_failures=True  creates real infra? no
  real_apply_smoke         command=apply (default) asserts=1 expect_failures=False creates real infra? YES
  uses_mock                command=apply           asserts=1 expect_failures=False creates real infra? no

real_apply_smoke has no command line, and it is the only one that would touch your account. Put plan-mode tests and apply-mode tests in separate files, so CI can run the cheap file on every pull request and the expensive one nightly. Next lesson covers mock providers, which make apply runs cheap too.

Running them

terraform test                          # all files
terraform test -filter=tests/web.tftest.hcl
terraform test -verbose                 # print the plan or state for each run
terraform test -junit-xml=results.xml   # for CI test reporters

These come from the command reference. The same page lists -json, -test-directory, -parallelism (default 10) and -run-parallelism (default 10). Runs can execute in parallel only when parallel = true is set, they do not reference each other’s outputs and they do not share a state file.

Terraform and OpenTofu

OpenTofu’s tofu test runs the same *.tftest.hcl files, and also *.tofutest.hcl. If both exist with the same base name, OpenTofu loads only the .tofutest one, so a module can ship tests for both tools. OpenTofu’s docs say the tofu command creates real infrastructure and destroys it afterward, the same warning Terraform has. Check the OpenTofu page for any attribute your tests use, because the two tools’ test features are not a perfect match. The current versions as I checked them on 28 November 2026 are Terraform 1.17.2 and OpenTofu 1.13.10.

About the video

The embed is Ned in the Cloud’s “Using the Terraform Test Framework”, 28 minutes 4 seconds, from May 2024. Its description says it covers why IaC testing is needed, the basic syntax of the framework, and building unit and integration tests, and it follows the framework’s release in Terraform 1.6. It was published before the later 1.x changes, so features added since then, such as mock support for ephemeral resources in 1.17, are not in it. I judged it English from title, description, channel and its English auto-caption track, and did not watch the whole video. HashiCorp’s 4-minute video in deeper is a short overview.

Where this fits

A test that applies real infrastructure is slow and needs credentials, so you write fewer of them. Mock providers make the test suite fast enough to run on every commit.

Check yourself

  1. 01A run block has no command line. What does it do?

    It uses the default, apply, so it creates real infrastructure and tries to destroy it at the end of the test file.

  2. 02How do you test that a variable validation rejects bad input?

    Write a run with command = plan, pass the bad value in variables and list the variable in expect_failures.

  3. 03How can a later run use an earlier run's result?

    By reading run.<name>.<output> in its variables or assertions.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark