Terragrunt Testing Patterns: Unit, Integration, and End-to-End Tests for DRY Infrastructure

Terragrunt Testing Patterns: Unit, Integration, and End-to-End Tests for DRY Infrastructure

Terragrunt adds DRY configuration management on top of Terraform: shared inputs, environment hierarchies, and dependency management. But the abstraction layer it introduces complicates testing. You can't just run terraform plan and call it done — you need to validate the rendered configuration, the dependency wiring, and the actual deployed resources across your account hierarchy.

This guide covers testing Terragrunt from unit-level config validation through full multi-environment integration tests.

Terragrunt Architecture Recap

A typical Terragrunt repository looks like:

infra-live/
├── terragrunt.hcl            # root config with provider, backend, account defaults
├── _envcommon/
│   ├── vpc.hcl               # shared VPC config
│   ├── eks.hcl               # shared EKS config
│   └── rds.hcl               # shared RDS config
├── dev/
│   ├── account.hcl           # dev account ID, region
│   ├── us-east-1/
│   │   ├── region.hcl
│   │   ├── vpc/
│   │   │   └── terragrunt.hcl
│   │   └── eks/
│   │       └── terragrunt.hcl
├── staging/
│   └── us-east-1/
│       ├── vpc/
│       │   └── terragrunt.hcl
│       └── eks/
│           └── terragrunt.hcl
└── prod/
    └── us-east-1/
        ├── vpc/
        │   └── terragrunt.hcl
        └── eks/
            └── terragrunt.hcl

Testing strategies map to this structure:

  1. Config rendering tests — does terragrunt render-json produce expected HCL?
  2. Plan-level tests — does terragrunt plan produce the expected resource changes?
  3. Mock output tests — do dependencies resolve correctly with mocked outputs?
  4. Integration tests — does terragrunt apply produce working infrastructure?

Unit Testing: Rendered Config Validation

The cheapest tests validate that Terragrunt renders configs correctly before touching a cloud provider.

Using terragrunt render-json

cd infra-live/dev/us-east-1/vpc
terragrunt render-json

This produces a JSON representation of the final rendered terragrunt.hcl. Test it in CI:

#!/bin/bash
# scripts/validate-render.sh

set -e

COMPONENT=$1
ENV=$2

cd "infra-live/${ENV}/us-east-1/${COMPONENT}"
terragrunt render-json --terragrunt-json-out rendered.json

# Validate expected fields
ACCOUNT_ID=$(jq -r '.inputs.account_id' rendered.json)
REGION=$(jq -r '.inputs.region' rendered.json)
ENVIRONMENT=$(jq -r '.inputs.environment' rendered.json)

[[ "$ACCOUNT_ID" == "123456789012" ]] || { echo "Wrong account ID for dev"; exit 1; }
[[ "$REGION" == "us-east-1" ]] || { echo "Wrong region"; exit 1; }
[[ "$ENVIRONMENT" == "dev" ]] || { echo "Wrong environment tag"; exit 1; }

echo "Render validation passed for ${ENV}/${COMPONENT}"

Terratest for Config Validation

// test/unit/render_test.go
package test

import (
    "encoding/json"
    "os"
    "os/exec"
    "path/filepath"
    "testing"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

type RenderedConfig struct {
    Inputs struct {
        AccountID   string `json:"account_id"`
        Region      string `json:"region"`
        Environment string `json:"environment"`
        VpcCidr     string `json:"vpc_cidr"`
    } `json:"inputs"`
    RemoteState struct {
        Config struct {
            Bucket string `json:"bucket"`
            Key    string `json:"key"`
        } `json:"config"`
    } `json:"remote_state"`
}

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

    componentPath := filepath.Join(
        "..", "..", "infra-live", "dev", "us-east-1", "vpc",
    )

    // Run terragrunt render-json
    cmd := exec.Command(
        "terragrunt", "render-json",
        "--terragrunt-json-out", "/tmp/vpc-dev.json",
        "--terragrunt-non-interactive",
    )
    cmd.Dir = componentPath
    out, err := cmd.CombinedOutput()
    require.NoError(t, err, "terragrunt render-json failed: %s", out)

    // Parse result
    data, err := os.ReadFile("/tmp/vpc-dev.json")
    require.NoError(t, err)

    var config RenderedConfig
    require.NoError(t, json.Unmarshal(data, &config))

    // Validate
    assert.Equal(t, "123456789012", config.Inputs.AccountID)
    assert.Equal(t, "us-east-1", config.Inputs.Region)
    assert.Equal(t, "dev", config.Inputs.Environment)
    assert.Contains(t, config.Inputs.VpcCidr, "10.0")  // dev uses 10.0.x.x

    // Backend state key should include environment
    assert.Contains(t, config.RemoteState.Config.Key, "dev")
    assert.Contains(t, config.RemoteState.Config.Key, "vpc")
}

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

    environments := []struct {
        env       string
        accountID string
        vpcCidr   string
    }{
        {"dev", "123456789012", "10.0"},
        {"staging", "234567890123", "10.1"},
        {"prod", "345678901234", "10.2"},
    }

    for _, tc := range environments {
        tc := tc
        t.Run(tc.env, func(t *testing.T) {
            t.Parallel()

            componentPath := filepath.Join(
                "..", "..", "infra-live", tc.env, "us-east-1", "vpc",
            )
            outFile := fmt.Sprintf("/tmp/vpc-%s.json", tc.env)

            cmd := exec.Command(
                "terragrunt", "render-json",
                "--terragrunt-json-out", outFile,
                "--terragrunt-non-interactive",
            )
            cmd.Dir = componentPath
            out, err := cmd.CombinedOutput()
            require.NoError(t, err, "render failed for %s: %s", tc.env, out)

            data, _ := os.ReadFile(outFile)
            var config RenderedConfig
            require.NoError(t, json.Unmarshal(data, &config))

            assert.Equal(t, tc.accountID, config.Inputs.AccountID,
                "%s should use account %s", tc.env, tc.accountID)
            assert.Contains(t, config.Inputs.VpcCidr, tc.vpcCidr,
                "%s VPC CIDR should start with %s", tc.env, tc.vpcCidr)
        })
    }
}

Mock Outputs for Dependency Testing

Terragrunt dependencies between components (VPC → EKS → RDS) create a challenge: you can't test EKS configuration without deploying VPC first. Mock outputs solve this.

Configuring Mock Outputs

# infra-live/dev/us-east-1/eks/terragrunt.hcl
dependency "vpc" {
  config_path = "../vpc"

  mock_outputs = {
    vpc_id         = "vpc-mock12345"
    private_subnets = ["subnet-mock1", "subnet-mock2", "subnet-mock3"]
    public_subnets  = ["subnet-pub1", "subnet-pub2", "subnet-pub3"]
  }

  mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}

inputs = {
  vpc_id          = dependency.vpc.outputs.vpc_id
  private_subnets = dependency.vpc.outputs.private_subnets
  cluster_name    = "dev-eks"
  cluster_version = "1.29"
}

Now terragrunt plan works without a deployed VPC:

cd infra-live/dev/us-east-1/eks
terragrunt plan --terragrunt-mock-auto-init

Testing Mock Output Resolution

// test/unit/mock_outputs_test.go
func TestEKSPlanWithMockedVPC(t *testing.T) {
    t.Parallel()

    componentPath := filepath.Join(
        "..", "..", "infra-live", "dev", "us-east-1", "eks",
    )

    // terragrunt plan with mocked dependencies
    cmd := exec.Command(
        "terragrunt", "plan",
        "--terragrunt-non-interactive",
        "--terragrunt-mock-auto-init",
        "-detailed-exitcode",
    )
    cmd.Dir = componentPath
    out, err := cmd.CombinedOutput()

    // exit code 0 = no changes, 1 = error, 2 = changes
    // We just want no error (not exit code 1)
    if exitErr, ok := err.(*exec.ExitError); ok {
        assert.NotEqual(t, 1, exitErr.ExitCode(),
            "Plan errored (not just changes): %s", out)
    }

    // Validate plan output references expected values
    assert.Contains(t, string(out), "dev-eks",
        "Plan should contain cluster name")
    assert.Contains(t, string(out), "1.29",
        "Plan should contain expected cluster version")
}

Integration Tests with Terratest

For full deploy-validate-destroy cycles, use Terratest:

// test/integration/vpc_test.go
package integration

import (
    "fmt"
    "testing"
    "time"

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

const TestEnvDir = "../../infra-test/us-east-1"  // separate test environment

func TestVPCDeployment(t *testing.T) {
    if testing.Short() {
        t.Skip("Skipping integration test in short mode")
    }

    t.Parallel()

    terragruntBinaryPath := "terragrunt"
    vpcDir := fmt.Sprintf("%s/vpc", TestEnvDir)

    // Defer destroy first (safety net)
    defer func() {
        shell.RunCommand(t, shell.Command{
            Command: terragruntBinaryPath,
            Args:    []string{"destroy", "--terragrunt-non-interactive", "-auto-approve"},
            WorkingDir: vpcDir,
            Logger: logger.Discard,
        })
    }()

    // Deploy
    _, err := shell.RunCommandAndGetOutputE(t, shell.Command{
        Command:    terragruntBinaryPath,
        Args:       []string{"apply", "--terragrunt-non-interactive", "-auto-approve"},
        WorkingDir: vpcDir,
    })
    require.NoError(t, err, "VPC apply failed")

    // Get outputs
    vpcID := terraform.Output(t, &terraform.Options{
        TerraformDir:    vpcDir,
        TerraformBinary: terragruntBinaryPath,
    }, "vpc_id")

    privateSubnets := terraform.OutputList(t, &terraform.Options{
        TerraformDir:    vpcDir,
        TerraformBinary: terragruntBinaryPath,
    }, "private_subnets")

    // Validate VPC exists
    vpc := aws.GetVpcById(t, vpcID, "us-east-1")
    assert.Equal(t, "10.0.0.0/16", vpc.CidrBlock)
    assert.Equal(t, "test", vpc.Tags["Environment"])

    // Validate subnets
    assert.Len(t, privateSubnets, 3, "Should have 3 private subnets")

    for _, subnetID := range privateSubnets {
        subnet := aws.GetSubnetById(t, subnetID, "us-east-1")
        assert.True(t, subnet.MapPublicIpOnLaunch == false,
            "Private subnets should not map public IPs")
    }
}

Testing the Full Stack with run-all

For testing a complete environment stack:

// test/integration/stack_test.go
func TestFullStackDeployment(t *testing.T) {
    if testing.Short() {
        t.Skip()
    }

    stackDir := "../../infra-test/us-east-1"

    // Deploy all components (respects dependency order)
    applyCmd := shell.Command{
        Command:    "terragrunt",
        Args:       []string{"run-all", "apply", "--terragrunt-non-interactive", "-auto-approve"},
        WorkingDir: stackDir,
        Env: map[string]string{
            "AWS_DEFAULT_REGION": "us-east-1",
        },
    }

    defer shell.RunCommand(t, shell.Command{
        Command:    "terragrunt",
        Args:       []string{"run-all", "destroy", "--terragrunt-non-interactive", "-auto-approve"},
        WorkingDir: stackDir,
    })

    _, err := shell.RunCommandAndGetOutputE(t, applyCmd)
    require.NoError(t, err, "Stack deployment failed")

    // Validate EKS cluster is healthy
    eksClusterName := terraform.Output(t, &terraform.Options{
        TerraformDir:    fmt.Sprintf("%s/eks", stackDir),
        TerraformBinary: "terragrunt",
    }, "cluster_name")

    cluster := aws.GetEksCluster(t, eksClusterName, "us-east-1")
    assert.Equal(t, "ACTIVE", cluster.Status)
}

Validating Environment Parity

A common Terragrunt bug: prod uses different input values than dev/staging because the _envcommon include was overridden differently. Test for parity:

// test/unit/parity_test.go
func TestEnvironmentParity(t *testing.T) {
    t.Parallel()

    components := []string{"vpc", "eks", "rds"}
    environments := []string{"dev", "staging", "prod"}

    // Fields that SHOULD be the same across environments
    parityFields := []string{
        "enable_flow_logs",
        "enable_deletion_protection",
        "cluster_version",
    }

    for _, component := range components {
        component := component
        t.Run(component, func(t *testing.T) {
            t.Parallel()

            configs := map[string]map[string]interface{}{}

            for _, env := range environments {
                dir := filepath.Join(
                    "..", "..", "infra-live", env, "us-east-1", component,
                )

                // Render config
                outFile := fmt.Sprintf("/tmp/%s-%s-parity.json", env, component)
                cmd := exec.Command(
                    "terragrunt", "render-json",
                    "--terragrunt-json-out", outFile,
                    "--terragrunt-non-interactive",
                )
                cmd.Dir = dir
                if _, err := cmd.CombinedOutput(); err != nil {
                    t.Skipf("Component %s doesn't exist in %s", component, env)
                }

                data, _ := os.ReadFile(outFile)
                var rendered map[string]interface{}
                json.Unmarshal(data, &rendered)

                inputs, _ := rendered["inputs"].(map[string]interface{})
                configs[env] = inputs
            }

            // Check parity fields
            for _, field := range parityFields {
                devVal := configs["dev"][field]
                stagingVal := configs["staging"][field]
                prodVal := configs["prod"][field]

                // All should match
                assert.Equal(t, devVal, stagingVal,
                    "%s.%s differs between dev and staging", component, field)
                assert.Equal(t, stagingVal, prodVal,
                    "%s.%s differs between staging and prod", component, field)
            }
        })
    }
}

CI Pipeline for Terragrunt Testing

# .github/workflows/terragrunt-tests.yml
name: Terragrunt Tests

on:
  pull_request:
    paths:
      - 'infra-live/**'
      - 'modules/**'

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: "1.7.0"
          terraform_wrapper: false

      - name: Install Terragrunt
        run: |
          wget -q https://github.com/gruntwork-io/terragrunt/releases/download/v0.55.0/terragrunt_linux_amd64
          chmod +x terragrunt_linux_amd64
          sudo mv terragrunt_linux_amd64 /usr/local/bin/terragrunt

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.21'
          cache: true

      - name: Run unit tests (render validation)
        run: go test ./test/unit/... -v -timeout 10m
        env:
          AWS_DEFAULT_REGION: us-east-1

      - name: Run parity tests
        run: go test ./test/unit/... -run TestEnvironmentParity -v

  integration-tests:
    runs-on: ubuntu-latest
    needs: unit-tests
    if: github.ref == 'refs/heads/main'  # only on merge to main
    environment: test-account
    steps:
      - uses: actions/checkout@v4

      - name: Configure AWS credentials (test account)
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::999999999999:role/github-actions-terragrunt-test
          aws-region: us-east-1

      - name: Run integration tests
        run: go test ./test/integration/... -v -timeout 60m
        env:
          AWS_DEFAULT_REGION: us-east-1

Terragrunt-Specific Testing Traps

Dependencies not mocked in CI: If mock_outputs_allowed_terraform_commands doesn't include validate, terragrunt validate will try to read real dependency outputs and fail. Always include validate in the allowed commands list.

run-all ordering in tests: terragrunt run-all apply respects dependency blocks for ordering. If your test bypasses this by deploying components manually, dependency outputs may not exist when downstream components apply.

State isolation: Integration tests must use isolated state backends. Never run integration tests against dev/staging state. Use a dedicated test account or workspace with unique state keys per test run:

# In test terragrunt.hcl
remote_state {
  backend = "s3"
  config = {
    bucket = "test-terragrunt-state"
    key    = "test-${get_env("TEST_RUN_ID", "local")}/${path_relative_to_include()}/terraform.tfstate"
  }
}

Slow feedback from render-json: Terragrunt still initializes provider plugins to render JSON. Speed this up by caching the .terragrunt-cache directory in CI and using --terragrunt-no-auto-init after first run.

Summary

Terragrunt testing has three tiers: render validation (fast, no cloud), plan testing with mocked outputs (fast, validates resource graph), and full integration tests (slow, validates actual infrastructure). Most issues are caught in the first two tiers. Run render and parity tests on every PR in under 5 minutes. Reserve full integration tests for merges to main, in a dedicated test account with ephemeral state.

The key to maintainable Terragrunt tests: render-json gives you a stable contract to assert against, mock outputs let you test dependency resolution without live infrastructure, and environment parity tests catch configuration drift before it reaches production.

Read more

Start now free