Unit testing in Terraform involves testing individual modules or resources in isolation to ensure they work as expected. This guide covers modern unit testing approaches for Terraform as of 2025.
Test Framework Options
1. Terratest
Terratest is the most popular testing framework for Terraform. Here's a basic example:
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestTerraformModule(t *testing.T) {
terraformOptions := &terraform.Options{
TerraformDir: "../examples/complete",
Vars: map[string]interface{}{
"environment": "test",
"region": "us-west-2",
},
}
// Clean up resources after the test
defer terraform.Destroy(t, terraformOptions)
// Deploy the infrastructure
terraform.InitAndApply(t, terraformOptions)
// Validate the outputs
output := terraform.Output(t, terraformOptions, "instance_id")
assert.NotEmpty(t, output)
}
2. Built-in Testing Framework
As of Terraform 1.6+, there's a built-in testing framework:
variables {
environment = "test"
region = "us-west-2"
}
run "verify_vpc_creation" {
command = plan
assert {
condition = aws_vpc.main.cidr_block == "10.0.0.0/16"
error_message = "VPC CIDR block must be 10.0.0.0/16"
}
}
run "verify_subnet_creation" {
command = plan
assert {
condition = length(aws_subnet.private) == 3
error_message = "Must create 3 private subnets"
}
}