Testing Terraform Infrastructure: Terratest, Checkov, and Contract Testing

Testing Terraform Infrastructure: Terratest, Checkov, and Contract Testing

Infrastructure as code brings software engineering discipline to cloud resources — and with it, the expectation of testing. A Terraform module that creates an S3 bucket with public ACLs, or an EKS cluster with overly permissive security groups, is a bug just as serious as a null pointer exception. The difference is it might not surface until an auditor finds it, or worse, a breach.

Testing Terraform happens at three levels: static analysis to catch policy violations before terraform plan, unit tests to verify module behavior in isolation, and integration tests that actually deploy and validate real infrastructure. This guide covers all three.

Static Analysis with Checkov and tfsec

Static analysis tools scan Terraform files without executing them. They check for known misconfigurations: public S3 buckets, unencrypted RDS instances, security groups open to the world.

Checkov

Checkov by Bridgecrew has 1000+ built-in checks for AWS, Azure, GCP, and Kubernetes.

pip install checkov
checkov -d ./terraform --framework terraform

Sample output for a vulnerable S3 bucket:

Check: CKV_AWS_21: "Ensure the S3 bucket has versioning enabled"
  FAILED for resource: aws_s3_bucket.data
  File: /terraform/main.tf:10-20

Check: CKV_AWS_145: "Ensure that S3 buckets are encrypted with KMS"
  FAILED for resource: aws_s3_bucket.data
  File: /terraform/main.tf:10-20

Integrate Checkov in CI:

# .github/workflows/terraform.yml
- name: Run Checkov
  uses: bridgecrewio/checkov-action@master
  with:
    directory: terraform/
    framework: terraform
    output_format: sarif
    output_file_path: checkov-results.sarif
    soft_fail: false
    check: CKV_AWS_21,CKV_AWS_145,CKV_AWS_18

- name: Upload Checkov SARIF
  uses: github/codeql-action/upload-sarif@v3
  if: always()
  with:
    sarif_file: checkov-results.sarif

Suppress false positives with inline comments:

resource "aws_s3_bucket" "access_logs" {
  # checkov:skip=CKV_AWS_21:Versioning not needed for access logs
  # checkov:skip=CKV_AWS_145:KMS encryption not required for low-sensitivity logs
  bucket = "my-access-logs-${var.environment}"
}

tfsec

tfsec focuses on security checks with clear severity levels:

brew install tfsec
tfsec ./terraform --format=json > tfsec-results.json
# GitHub Actions
- name: Run tfsec
  uses: aquasecurity/tfsec-action@v1.0.0
  with:
    working_directory: terraform/
    soft_fail: false
    format: sarif

Custom checks in tfsec:

# .tfsec/custom_checks.yml
checks:
  - code: CUS001
    description: Ensure all S3 buckets have a specific tag
    impact: Untagged buckets are hard to track and may incur unexpected costs
    resolution: Add required tags to all S3 buckets
    requiredTypes:
      - resource
    requiredLabels:
      - aws_s3_bucket
    severity: WARNING
    matchSpec:
      name: tags
      action: contains
      value: Environment

Unit Testing Terraform Modules with Terratest

Terratest is a Go library for writing automated tests that deploy real infrastructure, validate it, and tear it down. Despite the "real infrastructure" requirement, it's still considered unit/module testing because it tests a single module in isolation.

Setup

mkdir -p test
cd test
go mod init my-terraform-tests
go get github.com/gruntwork-io/terratest/modules/terraform
go get github.com/gruntwork-io/terratest/modules/aws
go get github.com/stretchr/testify/assert

Testing an S3 Module

Given a simple module:

# modules/s3-bucket/main.tf
variable "bucket_name" { type = string }
variable "environment" { type = string }

resource "aws_s3_bucket" "this" {
  bucket = var.bucket_name
  tags = {
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

resource "aws_s3_bucket_versioning" "this" {
  bucket = aws_s3_bucket.this.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "this" {
  bucket = aws_s3_bucket.this.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "aws:kms"
    }
  }
}

output "bucket_arn" { value = aws_s3_bucket.this.arn }
output "bucket_name" { value = aws_s3_bucket.this.bucket }

Write a Terratest test:

// test/s3_bucket_test.go
package test

import (
  "testing"
  "fmt"

  "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"
  "github.com/stretchr/testify/require"
)

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

  awsRegion := "us-east-1"
  bucketName := fmt.Sprintf("terratest-s3-%s", random.UniqueId())

  terraformOptions := &terraform.Options{
    TerraformDir: "../modules/s3-bucket",
    Vars: map[string]interface{}{
      "bucket_name": bucketName,
      "environment": "test",
    },
    EnvVars: map[string]string{
      "AWS_DEFAULT_REGION": awsRegion,
    },
  }

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

  // Verify outputs
  bucketArn := terraform.Output(t, terraformOptions, "bucket_arn")
  assert.Contains(t, bucketArn, bucketName)

  // Verify versioning is enabled
  versioningStatus := aws.GetS3BucketVersioning(t, awsRegion, bucketName)
  assert.Equal(t, "Enabled", versioningStatus)

  // Verify encryption
  sseConfig := aws.GetS3BucketServerSideEncryptionConfiguration(t, awsRegion, bucketName)
  require.NotNil(t, sseConfig)
  assert.Equal(t, "aws:kms", *sseConfig.Rules[0].ApplyServerSideEncryptionByDefault.SSEAlgorithm)

  // Verify tags
  tags := aws.GetTagsForS3Bucket(t, awsRegion, bucketName)
  assert.Equal(t, "test", tags["Environment"])
  assert.Equal(t, "terraform", tags["ManagedBy"])
}

Run the test:

cd test
go test -v -run TestS3BucketModule -timeout 30m

Testing Network Modules

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

  terraformOptions := &terraform.Options{
    TerraformDir: "../modules/vpc",
    Vars: map[string]interface{}{
      "vpc_cidr":           "10.0.0.0/16",
      "availability_zones": []string{"us-east-1a", "us-east-1b"},
      "environment":        "test",
    },
  }

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

  vpcId := terraform.Output(t, terraformOptions, "vpc_id")
  privateSubnets := terraform.OutputList(t, terraformOptions, "private_subnet_ids")
  publicSubnets := terraform.OutputList(t, terraformOptions, "public_subnet_ids")

  assert.NotEmpty(t, vpcId)
  assert.Len(t, privateSubnets, 2)
  assert.Len(t, publicSubnets, 2)

  // Verify public subnets have route to internet gateway
  awsRegion := "us-east-1"
  for _, subnetId := range publicSubnets {
    routeTable := aws.GetRouteTableForSubnet(t, awsRegion, subnetId, vpcId)
    igwExists := false
    for _, route := range routeTable.Routes {
      if route.GatewayId != nil && len(*route.GatewayId) > 0 {
        igwExists = true
      }
    }
    assert.True(t, igwExists, "Public subnet %s should have internet gateway route", subnetId)
  }
}

Retry Logic for Eventually Consistent Resources

Some AWS operations are eventually consistent. Terratest provides retry utilities:

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

maxRetries := 10
sleepBetweenRetries := 5 * time.Second

retry.DoWithRetry(t, "Wait for load balancer to be active", maxRetries, sleepBetweenRetries, func() (string, error) {
  lb := aws.GetLoadBalancer(t, awsRegion, lbArn)
  if lb.State.Code != "active" {
    return "", fmt.Errorf("Load balancer not yet active: %s", lb.State.Code)
  }
  return "active", nil
})

Plan-Based Testing: Assertions on terraform plan

Running terraform apply for every test is slow and costly. For many validations, checking the plan output is sufficient. This approach is especially useful for catching configuration drift and validating module interface changes.

Using terraform-plan-parser

Convert plan to JSON for assertions:

terraform init
terraform plan -out=tfplan
terraform show -json tfplan > plan.json

Assert on the plan with jq in CI:

# Verify no resources will be destroyed
DESTROYS=$(cat plan.json | jq '[.resource_changes[] | select(.change.actions[] == "delete")] | length')
if [ "$DESTROYS" -gt 0 ]; then
  echo "ERROR: Plan will destroy $DESTROYS resources"
  cat plan.json | jq '.resource_changes[] | select(.change.actions[] == "delete") | .address'
  exit 1
fi

# Verify expected resources will be created
CREATES=$(cat plan.json | jq '[.resource_changes[] | select(.change.actions[] == "create")] | length')
echo "Plan will create $CREATES resources"

OPA for Plan Assertions

Open Policy Agent (OPA) lets you write rich policies against the plan JSON:

# policies/terraform.rego
package terraform

# Deny if any S3 bucket is public
deny[msg] {
  resource := input.resource_changes[_]
  resource.type == "aws_s3_bucket"
  resource.change.after.acl == "public-read"
  msg := sprintf("S3 bucket %s has public-read ACL", [resource.address])
}

# Deny if any security group allows unrestricted ingress
deny[msg] {
  resource := input.resource_changes[_]
  resource.type == "aws_security_group_rule"
  resource.change.after.type == "ingress"
  resource.change.after.cidr_blocks[_] == "0.0.0.0/0"
  resource.change.after.to_port == 22
  msg := sprintf("Security group %s allows SSH from anywhere", [resource.address])
}

# Require all resources to have an Environment tag
deny[msg] {
  resource := input.resource_changes[_]
  resource.change.actions[_] == "create"
  not resource.change.after.tags.Environment
  msg := sprintf("Resource %s is missing required Environment tag", [resource.address])
}

Run OPA against the plan:

terraform show -json tfplan > plan.json
opa eval -d policies/ -i plan.json "data.terraform.deny" --format pretty

In CI:

- name: Terraform plan
  run: |
    terraform init
    terraform plan -out=tfplan
    terraform show -json tfplan > plan.json

- name: OPA policy check
  uses: open-policy-agent/opa-github-action@v2
  with:
    policy: policies/terraform.rego
    data: plan.json
    entrypoint: terraform/deny

Module Contract Testing

When Terraform modules are shared across teams, contract tests verify that the module's interface (inputs/outputs) remains stable:

// test/module_contract_test.go
func TestModuleOutputContract(t *testing.T) {
  terraformOptions := &terraform.Options{
    TerraformDir: "../modules/rds",
    Vars: map[string]interface{}{
      "db_name":       "testdb",
      "instance_class": "db.t3.micro",
      "environment":   "test",
    },
  }

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

  // Contract: these outputs MUST exist and be non-empty
  requiredOutputs := []string{
    "db_endpoint",
    "db_port",
    "db_arn",
    "security_group_id",
  }

  for _, output := range requiredOutputs {
    value := terraform.Output(t, terraformOptions, output)
    assert.NotEmpty(t, value, "Required output %s must not be empty", output)
  }

  // Contract: endpoint must be a valid hostname
  endpoint := terraform.Output(t, terraformOptions, "db_endpoint")
  assert.Regexp(t, `^[\w.-]+\.rds\.amazonaws\.com$`, endpoint)
}

Compliance Testing with Conftest

Conftest wraps OPA for a CI-friendly CLI:

brew install conftest
# policy/required_tags.rego
package main

required_tags := {"Environment", "Owner", "CostCenter"}

deny[msg] {
  resource := input.resource_changes[_]
  resource.change.actions[_] == "create"
  tag := required_tags[_]
  not resource.change.after.tags[tag]
  msg := sprintf("%s is missing required tag: %s", [resource.address, tag])
}
terraform show -json tfplan | conftest test -

CI Pipeline

name: Terraform CI
on: [pull_request]

jobs:
  static-analysis:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: bridgecrewio/checkov-action@master
        with:
          directory: terraform/
      - uses: aquasecurity/tfsec-action@v1.0.0
        with:
          working_directory: terraform/

  plan-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.TF_PLAN_ROLE }}
          aws-region: us-east-1
      - run: terraform init && terraform plan -out=tfplan
        working-directory: terraform/
      - run: terraform show -json tfplan > plan.json
        working-directory: terraform/
      - run: conftest test plan.json
        working-directory: terraform/

  terratest:
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version: "1.21" }
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.TF_APPLY_ROLE }}
          aws-region: us-east-1
      - run: go test -v -timeout 60m ./test/...

Conclusion

Testing Terraform requires layering approaches. Static analysis with Checkov and tfsec catches the obvious security misconfigurations before anything is deployed — add these as PR gate checks and eliminate entire classes of vulnerabilities. Plan-based testing with OPA or Conftest validates business rules (required tags, no public resources) without incurring apply costs. Terratest integration tests verify that modules actually create what they claim, with the correct attributes.

The investment pays off: a module tested at all three levels is one you can refactor confidently, share across teams, and deploy knowing it won't punch a hole in your security posture on the way up.

Read more

Start now free