Stage 4 · Provision
Terraform at Scale
Terratest Contracts
Go-based Terratest suites, fixture environments, retries, and teardown reliability — testing infrastructure with confidence.
Terratest Overview
Terratest is a Go library by Gruntwork for testing infrastructure. It provisions real infrastructure, validates it, and tears it down. Terratest is the industry standard for Terraform module testing because it tests the actual deployment, not just the configuration.
Test Structure
tests/
integration/
vpc_test.go
eks_test.go
rds_test.go
fixtures/
basic/
main.tf
variables.tf
complex/
main.tf
variables.tf
go.mod
go.sumThe tests directory contains Go test files and fixture directories. Each fixture is a minimal Terraform configuration that calls the module under test. The go.mod file manages dependencies.
Fixture Environments
module "vpc" {
source = "../../../modules/vpc"
cidr_block = var.cidr_block
enable_nat_gateway = var.enable_nat_gateway
}
variable "cidr_block" {
default = "10.0.0.0/16"
}
variable "enable_nat_gateway" {
default = true
}
output "vpc_id" {
value = module.vpc.vpc_id
}
output "private_subnet_ids" {
value = module.vpc.private_subnet_ids
}The fixture calls the real module with test-appropriate values. It exposes the outputs that the test will validate. Each fixture can have different configurations for different test scenarios.
Retries and Flaky Tests
Infrastructure tests are inherently flaky — API rate limits, eventual consistency, and transient errors cause failures. Terratest provides retry mechanisms to handle these issues gracefully.
Teardown Reliability
Teardown is the most critical part of Terratest. A failed teardown leaves infrastructure running and billing. Always use defer to ensure destroy runs even when the test fails.
Testing Contracts
t.Parallel() allows Go to run test functions concurrently. This significantly speeds up test suites with multiple test functions. Each test must have its own terraformOptions and fixture to avoid conflicts.
Terratest provisions real cloud resources. A test suite for an EKS module may create VPCs, subnets, and a cluster. Always run tests in a dedicated test account and ensure defer destroy is present.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.