Terraform Advanced — Terratest (Go)

less than 1 minute read

Integration testing that deploys real infrastructure, validates it, then destroys it.


Setup

mkdir test && cd test
go mod init test
go get github.com/gruntwork-io/terratest/modules/terraform

Basic Terratest

// test/vpc_test.go
package test

import (
    "testing"
    "github.com/gruntwork-io/terratest/modules/terraform"
    "github.com/stretchr/testify/assert"
)

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

    opts := &terraform.Options{
        TerraformDir: "../modules/vpc",
        Vars: map[string]interface{}{
            "vpc_cidr":    "10.99.0.0/16",
            "environment": "test",
        },
    }

    // Clean up after test
    defer terraform.Destroy(t, opts)

    // Deploy
    terraform.InitAndApply(t, opts)

    // Validate
    vpcId := terraform.Output(t, opts, "vpc_id")
    assert.Regexp(t, `^vpc-`, vpcId)
}

Run It

cd test
go test -v -timeout 30m

When to Use Terratest

✅ Module produces real AWS resources you need to validate
✅ Complex module interactions (VPC + subnets + NAT)
✅ Need to verify actual connectivity (HTTP checks, SSH)
❌ Simple variable validation → use terraform test
❌ Security scanning → use tfsec/Checkov

⚠️ Warning: Terratest creates real infrastructure and costs money. Always use defer terraform.Destroy() and run in isolated test accounts.


What’s Next?

Policy as code with Checkov and OPA.

← Terraform Test Framework Checkov, Conftest & OPA →

Updated: