InsightsInfrastructure as Code
Testing Terraform modules with terraform test
How to write fast plan-only unit tests with mock providers, slower integration tests that apply real resources in a sandbox account, and how to run both in CI without leaving orphaned infrastructure behind.
Published October 18, 20268 min read
Most shared Terraform modules are tested the same way: someone bumps the version in a staging stack, reads the plan and hopes. That catches typos. It does not catch a default that silently turns off encryption, a validation rule that accepts names the cloud provider will reject, or an output that changed shape and breaks three consumers on their next apply.
Terraform has shipped a native test framework since version 1.6, and mock providers since 1.7. Together they make it practical to test a module the way you would test a library: many cheap checks on every pull request, and a few expensive ones that create real resources. This article covers how to write both, how to run them in CI and what goes wrong.
How terraform test works
terraform test looks for files ending in .tftest.hcl in the configuration directory and in a tests directory beneath it (-test-directory changes that). Each file holds one or more run blocks, executed in order. A run plans or applies the module under test, then evaluates its assert blocks:
variables {
name = "payments-artifacts"
}
run "bucket_name_is_passed_through" {
command = plan
assert {
condition = aws_s3_bucket.this.bucket == "payments-artifacts"
error_message = "Bucket name must match var.name."
}
}Assertions can reference anything in the module, such as resources, locals, variables and outputs, as well as outputs of earlier run blocks.
Two defaults matter more than any other:
- The default
commandisapply. A run block withoutcommand = plancreates real infrastructure with whatever credentials are in the environment. - State lives with the test, not in your backend. At the end of each file Terraform destroys everything it created, in reverse run order. Nothing is written to the module's configured backend.
Two kinds of test
The framework supports both unit-style and integration-style tests, and a module needs both for different reasons.
| Unit tests | Integration tests | |
|---|---|---|
| Command | plan | apply |
| Provider | mock_provider | Real provider, sandbox account |
| Credentials | None | Short-lived, sandbox only |
| Runtime | Seconds | Minutes |
| Catches | Logic, defaults, validation, conditionals, output shape | API rejections, IAM gaps, eventual consistency, real attribute formats |
| Runs on | Every pull request | Merge to main, nightly, before a release |
Keep them in separate files so CI can run them separately:
modules/s3-bucket/
├── main.tf
├── variables.tf
├── outputs.tf
└── tests/
├── unit.tftest.hcl
├── integration.tftest.hcl
├── setup/
│ └── main.tf
└── verify/
└── main.tfUnit tests with mock providers
A plan against the real AWS provider still needs credentials, because data sources are read and the provider configures itself against the API. A mock_provider block replaces the provider entirely. Resources are "created" without any API call, and computed attributes get generated values: 0 for numbers, false for booleans, a random eight-character string for strings and empty collections.
Random strings are fine for most attributes, but not for ones your module parses or passes on. Give those realistic defaults:
mock_provider "aws" {
override_during = plan
mock_resource "aws_s3_bucket" {
defaults = {
arn = "arn:aws:s3:::payments-artifacts"
}
}
}
variables {
name = "payments-artifacts"
}
run "versioning_enabled_by_default" {
command = plan
assert {
condition = aws_s3_bucket_versioning.this.versioning_configuration[0].status == "Enabled"
error_message = "Versioning must be on unless explicitly disabled."
}
}
run "versioning_can_be_suspended" {
command = plan
variables {
versioning = false
}
assert {
condition = aws_s3_bucket_versioning.this.versioning_configuration[0].status == "Suspended"
error_message = "versioning = false must suspend versioning."
}
}
run "exposes_bucket_arn" {
command = plan
assert {
condition = output.arn == "arn:aws:s3:::payments-artifacts"
error_message = "The arn output must be the bucket ARN."
}
}By default, mocked values only appear during apply, so a plan sees computed attributes as (known after apply) and an assertion on output.arn cannot be evaluated. override_during = plan makes them available at plan time. Terraform 1.11 added support for mocked and overridden values in plan-only runs; on older versions those runs need command = apply against the mock, which is still free but slower.
When a single resource needs specific values, override_resource and override_data target it by address, and override_module replaces a child module's outputs without planning its contents. Shared mock definitions can live in .tfmock.hcl files and be loaded with source on the mock_provider block.
Testing validation with expect_failures
Variable validation, preconditions and postconditions are part of a module's interface, and they deserve tests as much as the happy path. expect_failures turns a failing custom condition into a passing test:
run "rejects_uppercase_names" {
command = plan
variables {
name = "Payments-Artifacts"
}
expect_failures = [
var.name,
]
}Only custom conditions can be expected to fail. A type error or a provider error still fails the test. Use it with command = plan: the condition fails during planning and there is nothing to apply.
A good rule for module authors: every validation block gets at least one test that triggers it and one that passes it. That is the cheapest way to stop a regex change from rejecting names that every existing consumer already uses.
Integration tests in a sandbox account
Integration tests apply the module for real. They need three things a unit test does not: unique names, a way to check the result from outside the module, and credentials that can only touch a sandbox.
A run block can execute a different module through its module block, which accepts local and registry sources. Use that for a setup module that generates unique names, and for a verification module that reads the result back through data sources:
resource "random_pet" "suffix" {
length = 2
}
output "name" {
value = "tftest-${random_pet.suffix.id}"
}provider "aws" {
region = "eu-west-1"
default_tags {
tags = {
"managed-by" = "terraform-test"
}
}
}
run "setup" {
module {
source = "./tests/setup"
}
}
run "create_bucket" {
variables {
name = run.setup.name
}
assert {
condition = aws_s3_bucket_public_access_block.this.block_public_policy
error_message = "Public policies must be blocked."
}
}
run "bucket_is_reachable" {
module {
source = "./tests/verify"
}
variables {
bucket = run.setup.name
}
assert {
condition = data.aws_s3_bucket.this.region == "eu-west-1"
error_message = "Bucket was not created in the expected region."
}
}The provider block at the root of the test file is passed into every run, so the tag lands on every resource the test creates. That tag is what makes cleanup possible when the test framework's own cleanup does not happen.
When cleanup fails
Terraform destroys test resources at the end of each file. Several things stop it:
- The job is cancelled or times out. A CI runner killed mid-test has no chance to destroy anything.
- The destroy itself fails. A bucket with objects written by another process, a deletion-protected database or a dependency created outside Terraform blocks the destroy. Terraform reports the resources it could not remove, and then they are yours to clean up.
- Multiple modules share resources in an unexpected order. Destroy runs in reverse order of the run blocks that last touched each state. With one setup module at the start, this rarely matters. With several helper modules, check the order before relying on it.
Plan for leftovers rather than hoping for none:
- Run integration tests in a dedicated sandbox account that holds nothing else.
- Tag every test resource through
default_tagsin the test file. - Run a scheduled sweeper that deletes tagged resources older than a few hours. The cloud-nuke and aws-nuke tools can do this with a tag filter, or a short script against the Resource Groups Tagging API.
- Give CI credentials that can only reach the sandbox, so a misconfigured test cannot touch anything that matters.
Running tests in CI
terraform test needs an initialized directory, because providers and the test helper modules have to be installed. A backend is not needed, so terraform init -backend=false is enough.
jobs:
unit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init -backend=false
working-directory: modules/s3-bucket
- run: terraform test -filter=tests/unit.tftest.hcl -junit-xml=unit.xml
working-directory: modules/s3-bucketThe integration job looks the same, with the integration file in -filter, a cloud credentials step for the sandbox account and a trigger on merges or a schedule rather than every pull request. -junit-xml, generally available since Terraform 1.11, writes a report that most CI systems can display per run block. -verbose prints the plan or state for each run, which helps when an assertion fails for reasons that are not obvious.
Since Terraform 1.12, run blocks can execute in parallel when parallel = true is set on the test block or on individual runs. A run only goes in parallel if it does not share a state file with, or reference the outputs of, another run in flight. That helps unit test files with many independent runs; integration files with a setup chain gain little.
What to test, and what to leave out
Tests are worth writing where a module makes decisions:
- Defaults that matter for security or cost: encryption, public access, deletion protection, instance sizes.
- Conditional resources behind feature switches, both on and off.
- Validation rules, in both directions.
- Outputs that consumers depend on, including their shape.
- Upgrades: a plan-only test of a
movedblock refactor can assert that no resource is replaced. See versioning Terraform modules for why that matters.
Do not test that the provider works. An assertion that aws_s3_bucket.this.bucket == var.name when the module does nothing but pass the value through adds runtime and no information. Organization-wide rules, such as "no public buckets anywhere", belong in policy checks on the plan, which cover every stack, not just the modules that remember to test it.
Where to start
- Pick the most widely used module and add a
tests/unit.tftest.hclwith a mock provider. - Add one test per validation rule and one per security-relevant default.
- Run unit tests on every pull request with
-junit-xml. - Set up a sandbox account, a tag convention and a sweeper before writing the first integration test.
- Add an integration test that applies the module once and verifies it from outside, and run it on merge.
- Make tests a requirement for a module release, next to
fmt,validateand the changelog.