Unit Testing IaC with Terratest
What you'll learn: How to write Go-based unit tests that validate your Terraform modules actually create and configure resources correctly before deploying to production.
Why Unit Test Infrastructure?
You've already validated syntax with terraform validate and caught style issues with linting. But how do you know your module actually works—that it creates the right resources with the correct settings? Unit testing infrastructure code deploys your Terraform to a real (but temporary) environment, verifies the results, then tears everything down.
What is Terratest?
Terratest is a Go library specifically designed for testing infrastructure code. Think of it as your infrastructure's quality assurance robot: it deploys your Terraform, pokes and prods the created resources to verify they match expectations, then cleans up after itself.
How It Works
- Deploy: Terratest runs
terraform applywith your module - Validate: Your Go test code checks actual resource properties (security group rules, EC2 instance types, S3 bucket policies)
- Destroy: Terratest runs
terraform destroyto clean up
Since Terratest uses Go's built-in testing framework, you write tests as standard Go functions. Each test typically provisions real infrastructure in a sandbox account, validates specific behaviors, then destroys everything.
The Value Proposition
Unlike static checks that only examine code structure, Terratest validates runtime behavior. It catches issues like incorrect AMI IDs, misconfigured security groups, or broken references between resources—problems that only surface during actual deployment.
Key Takeaway: Terratest provides automated unit testing for Terraform modules by deploying to real cloud environments, validating resource configuration, and automatically cleaning up—catching deployment issues before they reach production.