Terratest: Unit and Integration Testing for Terraform Modules in Go

Terratest: Unit and Integration Testing for Terraform Modules in Go

Infrastructure that isn't tested is infrastructure that breaks in production. Terraform modules are no different — you need automated tests that validate your modules work correctly before they ever touch a real environment. Terratest is the most widely adopted Go-based testing framework for Terraform, and this guide covers how to use it effectively for both unit and integration testing.

What Is Terratest?

Terratest is an open-source Go library maintained by Gruntwork that provides helper functions for testing infrastructure code. It supports Terraform, Packer, Docker, Kubernetes, and more. For Terraform specifically, Terratest lets you:

  • Deploy real infrastructure to a cloud provider
  • Run validations against it
  • Tear it down automatically after tests pass or fail

The "real infrastructure" part is both the strength and the cost. Terratest tests actually create AWS resources, GCP buckets, or Azure VMs — which means your tests catch real-world issues but also incur real cloud costs.

Setting Up Terratest

Prerequisites

You need Go installed (1.18+) and a working Terraform installation.

go version   # should be 1.18+
terraform version

Initialize a Go module for your test suite:

mkdir terraform-tests && cd terraform-tests
go mod init github.com/your-org/terraform-tests
go get github.com/gruntwork-io/terratest/modules/terraform
go get github.com/stretchr/testify/assert

Directory Structure

Keep tests alongside the modules they test:

modules/
  vpc/
    main.tf
    variables.tf
    outputs.tf
    test/
      vpc_test.go
  s3_bucket/
    main.tf
    outputs.tf
    test/
      s3_test.go

Writing Your First Terratest Test

Here's a basic test for an S3 bucket module:

package test

import (
    "testing"

    "github.com/gruntwork-io/terratest/modules/aws"
    "github.com/gruntwork-io/terratest/modules/random"
    "github.com/gruntwork-io/terratest/modules/terraform"
    "github.com/stretchr/testify/assert"
)

func TestS3BucketModule(t *testing.T) {
    t.Parallel()

    // Generate a unique bucket name to avoid conflicts
    bucketName := fmt.Sprintf("test-bucket-%s", random.UniqueId())
    awsRegion := "us-east-1"

    terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
        TerraformDir: "../",
        Vars: map[string]interface{}{
            "bucket_name": bucketName,
            "region":      awsRegion,
        },
    })

    // Ensure cleanup even if the test fails
    defer terraform.Destroy(t, terraformOptions)

    // Apply the module
    terraform.InitAndApply(t, terraformOptions)

    // Validate the bucket was created
    aws.AssertS3BucketExists(t, awsRegion, bucketName)

    // Validate versioning is enabled
    actualVersioning := aws.GetS3BucketVersioning(t, awsRegion, bucketName)
    assert.Equal(t, "Enabled", actualVersioning)
}

Key patterns here:

  • t.Parallel() — run tests concurrently to save time
  • random.UniqueId() — prevent naming conflicts between test runs
  • defer terraform.Destroy(...) — always clean up, even on failure
  • terraform.WithDefaultRetryableErrors() — auto-retry on transient API errors

Unit Testing vs Integration Testing

Unit Tests (Terraform Plan Only)

For fast feedback without cloud costs, test the Terraform plan output instead of applying:

func TestVPCModulePlan(t *testing.T) {
    t.Parallel()

    terraformOptions := &terraform.Options{
        TerraformDir: "../",
        Vars: map[string]interface{}{
            "cidr_block":   "10.0.0.0/16",
            "environment":  "test",
        },
    }

    // Plan only — no real infrastructure created
    planOutput := terraform.InitAndPlan(t, terraformOptions)

    // Assert on plan output
    assert.Contains(t, planOutput, "aws_vpc.main will be created")
    assert.Contains(t, planOutput, "aws_subnet.private")
}

Plan-only tests run in seconds and don't incur costs. They're ideal for validating:

  • Resource names and tags
  • Variable validation logic
  • Conditional resource creation
  • Output values (via terraform output -json)

Integration Tests (Full Apply)

Integration tests deploy real infrastructure and validate it works end-to-end:

func TestVPCConnectivity(t *testing.T) {
    t.Parallel()

    terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
        TerraformDir: "../",
        Vars: map[string]interface{}{
            "cidr_block":  "10.1.0.0/16",
            "environment": "test",
        },
    })

    defer terraform.Destroy(t, terraformOptions)
    terraform.InitAndApply(t, terraformOptions)

    // Fetch outputs
    vpcId := terraform.Output(t, terraformOptions, "vpc_id")
    subnetIds := terraform.OutputList(t, terraformOptions, "private_subnet_ids")

    // Validate via AWS SDK
    assert.NotEmpty(t, vpcId)
    assert.Equal(t, 3, len(subnetIds))

    // Validate route tables
    awsRegion := "us-east-1"
    for _, subnetId := range subnetIds {
        routeTable := aws.GetRouteTableForSubnet(t, awsRegion, subnetId)
        assert.NotNil(t, routeTable)
    }
}

Testing Strategies That Actually Work

Test Stages with defer Chains

When you have multiple dependent resources, use staged teardown:

func TestCompleteStack(t *testing.T) {
    t.Parallel()

    networkOptions := &terraform.Options{TerraformDir: "../network"}
    appOptions := &terraform.Options{TerraformDir: "../app"}

    defer terraform.Destroy(t, appOptions)    // destroy app first
    defer terraform.Destroy(t, networkOptions) // then network

    terraform.InitAndApply(t, networkOptions)
    vpcId := terraform.Output(t, networkOptions, "vpc_id")

    appOptions.Vars = map[string]interface{}{"vpc_id": vpcId}
    terraform.InitAndApply(t, appOptions)

    // Validate the stack
    albDns := terraform.Output(t, appOptions, "alb_dns_name")
    http_helper.HttpGetWithRetry(t, "http://"+albDns, nil, 200, "Hello", 10, 5*time.Second)
}

Retry Logic for Eventual Consistency

AWS resources often take time to become available. Use Terratest's retry helpers:

import "github.com/gruntwork-io/terratest/modules/retry"

retry.DoWithRetry(t, "wait for ALB", 10, 30*time.Second, func() (string, error) {
    resp, err := http.Get("http://" + albDns)
    if err != nil || resp.StatusCode != 200 {
        return "", fmt.Errorf("ALB not ready yet")
    }
    return "ok", nil
})

Test Fixtures

Create minimal fixture modules specifically for testing:

test/
  fixtures/
    complete/
      main.tf     # references the real module with test vars
    minimal/
      main.tf     # tests only required variables
# test/fixtures/complete/main.tf
module "s3_bucket" {
  source      = "../../../"  # points to the real module
  bucket_name = var.bucket_name
  versioning  = true
  encryption  = true
}

Running Tests

# Run all tests
cd modules/vpc/test
go test -v -timeout 30m

# Run a specific test
go test -v -run TestVPCConnectivity -timeout 30m

# Run tests in parallel (default Go behavior with t.Parallel())
go test -v -parallel 10 -timeout 60m

Always set a generous timeout. Real infrastructure provisioning can take 5-20 minutes depending on the resources.

Cost Management

Terratest tests cost real money. Keep costs down:

  • Use plan-only tests for logic validation
  • Use cheap resources in integration tests (t3.micro, minimal storage)
  • Always defer destroy — leaked resources are budget killers
  • Use test-specific AWS accounts with budget alerts
  • Tag all test resources with CreatedBy: terratest and sweep stale ones
// Tag everything for easy cleanup
terraformOptions := &terraform.Options{
    EnvVars: map[string]string{
        "TF_VAR_tags": `{"CreatedBy":"terratest","Environment":"test"}`,
    },
}

CI/CD Integration

In GitHub Actions:

name: Terraform Tests
on: [pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.21'
      - uses: hashicorp/setup-terraform@v3

      - name: Run Terratest
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        run: |
          cd modules/vpc/test
          go test -v -timeout 30m

Common Pitfalls

Flaky tests from naming conflicts — always use random.UniqueId() for resource names.

Tests that don't clean up — add defer terraform.Destroy() as the first thing after InitAndApply.

Timeouts too short — 30 minutes minimum for integration tests; some resources (RDS, EKS) need 60+.

No parallelism — not calling t.Parallel() means your test suite takes 10x longer than it should.

Testing the wrong thing — unit-test Terraform logic (variables, conditionals, outputs) and integration-test actual behavior (can the EC2 instance reach the database?). Don't just assert resources exist.

Terratest vs Other Approaches

Approach Speed Cost Confidence
terraform plan Fast Free Low
Terratest (plan) Fast Free Medium
Terratest (apply) Slow ~$1-10/run High
Manual testing Slowest Variable Depends

For most teams: run plan-only tests on every PR and full integration tests nightly or on merge to main.


Terratest gives you the highest confidence that your Terraform modules actually work — because they test against real infrastructure. The tradeoff is speed and cost, but with good test design (fixtures, parallelism, plan-only for logic), you can keep both manageable. Start with plan tests, add integration tests for your most critical modules, and build from there.

Read more

Start now free