Terraform Built-In Testing Framework: Write and Run Tests with .tftest.hcl
HashiCorp added a native testing framework to Terraform in version 1.6. Before this, testing Terraform required third-party tools like Terratest (Go) or Kitchen-Terraform (Ruby). Now you can write tests in HCL itself, run them with terraform test, and validate your modules without leaving the Terraform ecosystem.
This guide covers everything you need to know about .tftest.hcl files, the terraform test command, and how to write meaningful tests for your modules.
What Changed in Terraform 1.6
The native testing framework was introduced as experimental in 1.5 and stabilized in 1.6. Key capabilities:
- Write tests in HCL (
.tftest.hclfiles) - Run
terraform testto execute them - Use
runblocks to apply configurations and assert outputs - Test with real infrastructure or plan-only (no apply)
- Override providers and variables per test file
- Use
mock_providerblocks for unit testing without real cloud resources
File Structure
Tests live in a tests/ directory by default, or directly alongside your modules:
modules/
vpc/
main.tf
variables.tf
outputs.tf
tests/
unit.tftest.hcl
integration.tftest.hclYou can also put .tftest.hcl files in the root module directory.
Your First .tftest.hcl File
Here's a minimal test that validates a VPC module's outputs:
# tests/vpc_test.tftest.hcl
variables {
cidr_block = "10.0.0.0/16"
environment = "test"
}
run "vpc_is_created" {
command = plan
assert {
condition = aws_vpc.main.cidr_block == "10.0.0.0/16"
error_message = "VPC CIDR block does not match the input variable"
}
assert {
condition = aws_vpc.main.tags["Environment"] == "test"
error_message = "VPC is missing the Environment tag"
}
}
run "subnets_are_created" {
command = plan
assert {
condition = length(aws_subnet.private) == 3
error_message = "Expected 3 private subnets, got ${length(aws_subnet.private)}"
}
}Run it:
terraform testOutput:
tests/vpc_test.tftest.hcl... in progress
run "vpc_is_created"... pass
run "subnets_are_created"... pass
tests/vpc_test.tftest.hcl... tsucceed
Success! 2 passed, 0 failed.The run Block in Detail
Each run block represents a test case. It can:
run "descriptive_test_name" {
# command = plan | apply (default: apply)
command = plan
# Override variables for this specific run
variables {
instance_type = "t3.micro"
}
# Override module inputs
module {
source = "./modules/vpc"
}
# Assertions
assert {
condition = output.vpc_id != ""
error_message = "VPC ID should not be empty"
}
}command = plan vs command = apply
command = plan— fast, no cloud resources, tests planned valuescommand = apply— creates real infrastructure, tests actual outputs
For most unit testing, command = plan is sufficient and much faster. Use command = apply when you need to validate that resources actually work (e.g., can an EC2 instance reach an RDS endpoint).
Testing Outputs
Access module outputs in your assertions:
# modules/s3_bucket/outputs.tf
output "bucket_name" {
value = aws_s3_bucket.main.bucket
}
output "bucket_arn" {
value = aws_s3_bucket.main.arn
}# tests/s3_test.tftest.hcl
variables {
bucket_name = "my-test-bucket-12345"
region = "us-east-1"
}
run "bucket_outputs_are_correct" {
command = plan
assert {
condition = output.bucket_name == "my-test-bucket-12345"
error_message = "Bucket name output doesn't match input"
}
assert {
condition = can(regex("^arn:aws:s3:::", output.bucket_arn))
error_message = "Bucket ARN should start with arn:aws:s3:::"
}
}Mock Providers for Unit Testing
The biggest feature of the native framework for unit testing is mock_provider. It lets you write tests without real cloud credentials:
# tests/unit.tftest.hcl
mock_provider "aws" {}
run "vpc_plan_succeeds" {
command = plan
assert {
condition = aws_vpc.main.cidr_block == var.cidr_block
error_message = "VPC CIDR mismatch"
}
}With mock_provider, Terraform generates fake values for all computed attributes (IDs, ARNs, etc.). This is ideal for:
- Testing conditional logic
- Validating variable validation rules
- CI pipelines that don't have cloud credentials
- Developers who don't have access to AWS accounts
You can also override specific attributes in the mock:
mock_provider "aws" {
mock_resource "aws_vpc" {
defaults = {
id = "vpc-mock12345"
owner_id = "123456789012"
}
}
}Testing Variable Validation
If your module uses variable validation blocks, you can test that invalid inputs are rejected:
# modules/vpc/variables.tf
variable "cidr_block" {
type = string
validation {
condition = can(cidrhost(var.cidr_block, 0))
error_message = "cidr_block must be a valid CIDR notation"
}
}# tests/validation_test.tftest.hcl
mock_provider "aws" {}
run "valid_cidr_passes" {
command = plan
variables {
cidr_block = "10.0.0.0/16"
}
# No assertions needed — if plan succeeds, validation passed
}
run "invalid_cidr_fails" {
command = plan
variables {
cidr_block = "not-a-cidr"
}
expect_failures = [
var.cidr_block,
]
}The expect_failures block is how you test that validation correctly rejects bad input. The test passes only if the specified check fails.
Chaining Run Blocks
Run blocks within a file execute sequentially and can reference outputs from previous runs:
# tests/integration.tftest.hcl
run "create_network" {
command = apply
variables {
env = "test"
}
}
run "create_application" {
command = apply
variables {
vpc_id = run.create_network.vpc_id # reference previous run output
}
assert {
condition = output.app_url != ""
error_message = "App URL should be set after deployment"
}
}State is shared between run blocks in the same file — resources created in create_network persist when create_application runs.
Setup and Teardown
There's no explicit setup/teardown syntax, but you control it through run block order and the command type. For cleanup:
# Run tests (applies and destroys automatically)
terraform test
# Run tests without destroying (for debugging)
terraform test -verbose
# Run specific test file
terraform test -filter=tests/unit.tftest.hclBy default, terraform test destroys all applied resources after tests complete — even if tests fail. This is the correct behavior for CI.
Integration with CI/CD
# .github/workflows/terraform-test.yml
name: Terraform Tests
on: [pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: "1.6.0"
- name: Terraform Init
run: terraform init
working-directory: modules/vpc
- name: Run Unit Tests (no credentials needed)
run: terraform test -filter=tests/unit.tftest.hcl
working-directory: modules/vpc
- name: Run Integration Tests
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
run: terraform test -filter=tests/integration.tftest.hcl
working-directory: modules/vpcWhen to Use Native Testing vs Terratest
| Feature | Native (.tftest.hcl) | Terratest (Go) |
|---|---|---|
| No extra tools | ✅ | ❌ Requires Go |
| Mock providers | ✅ | ❌ |
| Real infra testing | ✅ | ✅ |
| HTTP/TCP validation | ❌ | ✅ |
| SSH into instances | ❌ | ✅ |
| Custom assertions | Limited | Full Go stdlib |
| Learning curve | Low | High |
The native framework is excellent for:
- Module logic testing
- Variable validation
- Output format testing
- Plan-only unit tests with mocks
Use Terratest when you need to:
- Make HTTP requests to deployed endpoints
- SSH into instances to validate config
- Write complex multi-stage test logic
- Validate cross-module integration with custom logic
Common Patterns
Test naming: Use descriptive names that read like specifications: "vpc_creates_exactly_three_subnets" not "test1".
Separate unit and integration: Keep unit.tftest.hcl (mock_provider, plan-only) separate from integration.tftest.hcl (real AWS, apply). Run unit tests on every PR, integration tests on merge.
Test edge cases: Test with minimum required variables, maximum values, and invalid inputs (using expect_failures).
Don't test Terraform itself: Don't write tests that just assert aws_vpc.main will be created. Test your module's logic — the right CIDR, the right tags, the correct number of subnets based on your variable inputs.
The Terraform native testing framework removes the excuse not to test your modules. No Go knowledge required, no extra dependencies, just HCL you already know. Start with mock_provider unit tests for your most critical modules today — they run in seconds and catch regressions before they reach production.