Unit Testing with Terratest
Learn to write unit tests for your Terraform modules using Terratest, a Go library for testing infrastructure code.
Unit Testing with Terratest is a free DevOps Bootcamp lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the DevOps Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Test Your IaC?
Infrastructure as Code (IaC) allows you to manage infrastructure like software. Just like software, IaC configurations can have bugs!
- Reliability: Catch errors before deployment.
- Consistency: Ensure resources are provisioned as expected.
- Confidence: Make changes with less fear of breaking existing infrastructure.
Testing your Terraform code is crucial for building robust and maintainable cloud environments.
Unit vs. Integration Tests
When testing IaC, we often talk about two main types:
- Unit Tests: Focus on small, isolated parts of your code, like a single Terraform module. They ensure individual components work correctly in isolation.
- Integration Tests: Verify that multiple components or modules work together as a system, often deploying real resources to a cloud environment.
In this lesson, we'll focus on unit testing your Terraform modules.
Introducing Terratest
Terratest is a Go library developed by HashiCorp (the creators of Terraform) specifically designed for testing infrastructure code.
- It helps you write automated tests for your Terraform, Packer, Kubernetes, and other IaC code.
- Terratest can deploy real infrastructure to your cloud provider, run assertions against it, and then clean it up.
- It's powerful for both unit and integration testing.
Terratest Prerequisites
To get started with Terratest, you'll need a few things:
- Go: Terratest is a Go library, so you need Go installed (version 1.13 or higher recommended).
- Terraform CLI: The Terraform command-line interface must be installed and accessible.
- Cloud Provider Credentials: If you're deploying real resources (even for unit tests that touch a cloud API), you'll need authenticated cloud provider access (e.g., AWS CLI configured).
You'll also need basic familiarity with Go programming concepts.
Go Test File Structure
Terratest tests are written in Go and follow Go's standard testing conventions:
- Test files end with
_test.go(e.g.,main_test.go). - Test functions start with
Test(e.g.,TestMyModule(t *testing.T)). - They use Go's built-in
testingpackage.
These files typically sit alongside your Terraform module or in a dedicated test directory.
`terraform.Options` Explained
The core of a Terratest Terraform test is the terraform.Options struct. This object tells Terratest how to run Terraform.
Key fields include:
TerraformDir: Path to your Terraform module.Vars: Input variables for your Terraform module.EnvVars: Environment variables to set for the Terraform process.BackendConfig: Configuration for your Terraform backend.
It's your blueprint for executing Terraform commands within the test.
Basic Test Workflow
A typical Terratest unit test for Terraform follows these steps:
- Define Options: Create a
terraform.Optionsstruct pointing to your module and setting variables. - Deploy: Use
terraform.InitAndApply(t, options)to initialize and apply your configuration. - Defer Destroy: Immediately add
defer terraform.Destroy(t, options)to ensure cleanup after the test runs. - Assert: Use Go's
testify/assertor Terratest'sterraform.Outputto check resource properties or outputs.
This ensures a clean, isolated test environment.
Coding `terraform.Options`
Here's a simple Go program demonstrating how to set up terraform.Options. This is a foundational step for any Terratest interaction.
package main
import (
"fmt"
"path/filepath"
"github.com/gruntwork-io/terratest/modules/terraform"
)
func main() {
// Define the path to your Terraform configuration directory.
// In a real test, this would point to your module under test.
terraformConfigDir := filepath.Join(".", "my-example-module")
// Create a terraform.Options object.
// This struct holds all the configuration for running Terraform via Terratest.
options := &terraform.Options{
TerraformDir: terraformConfigDir,
// You would add input variables here, e.g.:
// Vars: map[string]interface{}{"instance_type": "t2.micro"},
// And environment variables, e.g.:
// EnvVars: map[string]string{"AWS_REGION": "us-east-1"},
}
fmt.Println("--- Terratest Options Configuration Demo ---")
fmt.Printf("Configured Terraform Directory: %s\n", options.TerraformDir)
fmt.Println("This shows how to initialize Terratest options.")
fmt.Println("Actual Terratest unit tests are run using 'go test' command.")
}Asserting Outputs
After applying your Terraform configuration, you'll want to verify its outputs. Terratest provides functions to easily retrieve these values.
terraform.Output(t, options, "output_name"): Retrieves a single string output.terraform.OutputMap(t, options, "output_name"): Retrieves a map output.terraform.OutputList(t, options, "output_name"): Retrieves a list output.
You then use Go's testing assertions (e.g., from github.com/stretchr/testify/assert) to check if the outputs match your expectations.
Check Your Understanding
Terratest helps you test your Terraform code by interacting with real cloud resources. Which of the following is NOT a typical step in a Terratest unit test workflow?
Recap & Next Steps
You've learned the fundamentals of unit testing Terraform with Terratest!
- Terratest is a Go library for testing IaC.
- It enables you to deploy, assert, and clean up real cloud infrastructure.
- Key components include
_test.gofiles,func TestXxx(t *testing.T), and theterraform.Optionsstruct. - The workflow involves defining options, applying Terraform, making assertions, and ensuring cleanup with
defer.
Next, explore how to write more complex assertions and integrate Terratest into your CI/CD pipelines for automated testing.
Frequently asked questions
Is the “Unit Testing with Terratest” lesson free?
Yes — the full text of “Unit Testing with Terratest” is free to read here on the web, and the DevOps Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the DevOps Bootcamp course, upgrade to CoddyKit PRO.
What will I learn in “Unit Testing with Terratest”?
Learn to write unit tests for your Terraform modules using Terratest, a Go library for testing infrastructure code. You practise DevOps Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start DevOps Bootcamp?
No prior experience is required. DevOps Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Unit Testing with Terratest” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this DevOps Bootcamp lesson?
Yes. Every DevOps Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Terraform `validate` and `fmt`
- Unit Testing with Terratest
- Integration Testing Cloud Resources
- Policy as Code and Compliance Checks