Terragrunt Mock Inputs and Before/After Hooks: Testing Multi-Environment IaC
Terragrunt makes Terraform DRY — but it adds its own layer of complexity that also needs testing. mock_inputs let you test module configurations without resolving real dependencies. Before/after hooks let you validate state before and after applies. Together, they give you a fast feedback loop for multi-environment infrastructure changes.
This post covers Terragrunt-specific testing patterns that go beyond what Terratest covers.
Why Terragrunt Needs Its Own Testing Strategy
If your infrastructure uses Terragrunt's dependency blocks, a standard terraform plan will fail unless all dependencies are already deployed:
# services/api/terragrunt.hcl
dependency "vpc" {
config_path = "../../networking/vpc"
# Without mock_outputs, this fails if VPC isn't deployed
}
inputs = {
vpc_id = dependency.vpc.outputs.vpc_id
subnet_ids = dependency.vpc.outputs.private_subnet_ids
}mock_outputs solve this by providing fake values when the dependency isn't deployed:
dependency "vpc" {
config_path = "../../networking/vpc"
mock_outputs = {
vpc_id = "vpc-mock12345"
private_subnet_ids = ["subnet-mock1", "subnet-mock2"]
}
mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}Mock Inputs for Isolated Testing
The pattern for testing individual modules in isolation:
# services/api/terragrunt.hcl
locals {
env = read_terragrunt_config(find_in_parent_folders("env.hcl"))
}
dependency "vpc" {
config_path = "../../networking/vpc"
mock_outputs = {
vpc_id = "vpc-00000000000000001"
private_subnet_ids = ["subnet-00000000000000001", "subnet-00000000000000002"]
public_subnet_ids = ["subnet-00000000000000003", "subnet-00000000000000004"]
}
mock_outputs_allowed_terraform_commands = ["validate", "plan", "apply"]
}
dependency "rds" {
config_path = "../../data/rds"
mock_outputs = {
endpoint = "mock-db.cluster-xxxxxxxx.us-east-1.rds.amazonaws.com"
port = 5432
db_name = "appdb"
}
mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}
inputs = {
vpc_id = dependency.vpc.outputs.vpc_id
subnet_ids = dependency.vpc.outputs.private_subnet_ids
db_endpoint = dependency.rds.outputs.endpoint
environment = local.env.locals.environment
}With this setup, terragrunt plan runs without errors even when VPC and RDS aren't deployed.
Before/After Hooks for Test Automation
Terragrunt hooks run shell commands before or after Terraform operations. Use them for pre-flight checks and post-deployment validation:
# terragrunt.hcl with testing hooks
terraform {
source = "../../modules//api-service"
before_hook "validate_inputs" {
commands = ["plan", "apply"]
execute = ["bash", "-c", "${get_terragrunt_dir()}/scripts/validate-inputs.sh"]
}
before_hook "check_prerequisites" {
commands = ["apply"]
execute = ["bash", "-c", "aws sts get-caller-identity > /dev/null && echo 'AWS credentials valid'"]
}
after_hook "run_smoke_tests" {
commands = ["apply"]
execute = ["bash", "-c", "${get_terragrunt_dir()}/scripts/smoke-test.sh"]
run_on_error = false # Only run if apply succeeded
}
after_hook "notify_on_failure" {
commands = ["apply"]
execute = ["bash", "-c", "${get_terragrunt_dir()}/scripts/notify-failure.sh"]
run_on_error = true # Run even if apply failed
}
}Input Validation Hook
#!/bin/bash
# scripts/validate-inputs.sh
# Read terragrunt inputs
INPUTS=$(terragrunt output-all 2>/dev/null || echo "{}")
# Validate environment name
ENV=$(echo $TF_VAR_environment)
if [[ ! $ENV =~ ^(dev|staging|prod)$ ]]; then
echo "❌ Invalid environment: $ENV. Must be dev, staging, or prod"
exit 1
fi
# Validate instance sizes for prod
if [[ $ENV == "prod" ]]; then
INSTANCE_CLASS=$(echo $TF_VAR_instance_class)
if [[ $INSTANCE_CLASS == "db.t3.micro" ]]; then
echo "❌ db.t3.micro not allowed in production"
exit 1
fi
fi
echo "✅ Input validation passed"Smoke Test Hook
#!/bin/bash
# scripts/smoke-test.sh — runs after successful apply
# Get outputs from the just-applied stack
API_URL=$(terragrunt output -raw api_endpoint 2>/dev/null)
if [ -z "$API_URL" ]; then
echo "⚠️ No api_endpoint output — skipping smoke test"
exit 0
fi
echo "Running smoke test against $API_URL..."
# Health check
HTTP_STATUS=$(curl -sf -o /dev/null -w "%{http_code}" "$API_URL/health" 2>/dev/null)
if [ "$HTTP_STATUS" == "200" ]; then
echo "✅ Smoke test passed: $API_URL/health returned 200"
else
echo "❌ Smoke test failed: $API_URL/health returned $HTTP_STATUS"
exit 1
fiTesting Multi-Environment Configurations
For DRY multi-environment setups, test that environments share the right configuration and differ where expected:
#!/bin/bash
# test-env-configs.sh — validate environment-specific configs
ENVS=("dev" "staging" "prod")
PASSED=0
FAILED=0
for ENV in "${ENVS[@]}"; do
echo "=== Testing $ENV configuration ==="
cd "environments/$ENV"
# Run validate (fast, no API calls)
if terragrunt validate-all 2>&1 | grep -q "Error"; then
echo "❌ $ENV: validate-all failed"
FAILED=$((FAILED+1))
else
echo "✅ $ENV: validate-all passed"
PASSED=$((PASSED+1))
fi
# Run plan with mock outputs (catches dependency issues)
if terragrunt plan-all --terragrunt-ignore-external-dependencies 2>&1 | grep -q "Error"; then
echo "❌ $ENV: plan-all failed"
FAILED=$((FAILED+1))
else
echo "✅ $ENV: plan-all passed"
PASSED=$((PASSED+1))
fi
cd ../..
done
echo ""
echo "Results: $PASSED passed, $FAILED failed"
[ $FAILED -eq 0 ] && exit 0 || exit 1The run_cmd Function for Dynamic Testing
Terragrunt's run_cmd function executes commands during configuration parsing. Use it to validate external state:
# terragrunt.hcl
locals {
# Verify required SSM parameters exist before running
_validate_ssm = run_cmd(
"bash", "-c",
"aws ssm get-parameter --name '/app/${local.env}/db_password' > /dev/null && echo 'ok' || (echo 'Missing SSM parameter' && exit 1)"
)
# Get current account ID to validate we're in the right account
account_id = run_cmd("aws", "sts", "get-caller-identity", "--query", "Account", "--output", "text")
env = read_terragrunt_config(find_in_parent_folders("env.hcl"))
}
# Validate we're in the correct AWS account for this environment
inputs = {
expected_account = local.env.locals.aws_account_id
actual_account = local.account_id
}# modules/account-check/main.tf
variable "expected_account" {}
variable "actual_account" {}
resource "null_resource" "account_check" {
triggers = {
always = timestamp()
}
provisioner "local-exec" {
command = <<-EOF
if [ "${var.actual_account}" != "${var.expected_account}" ]; then
echo "ERROR: Wrong AWS account. Expected ${var.expected_account}, got ${var.actual_account}"
exit 1
fi
echo "Account check passed: ${var.actual_account}"
EOF
}
}Testing Terragrunt Modules with Terratest
For integration tests that actually deploy resources:
// test/api_service_test.go
package test
import (
"testing"
"time"
"net/http"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/gruntwork-io/terratest/modules/http-helper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAPIServiceModule(t *testing.T) {
t.Parallel()
terraformOptions := &terraform.Options{
// Point to Terragrunt config, not module directly
TerraformDir: "../environments/test/services/api",
TerraformBinary: "terragrunt",
// Override inputs for test
Vars: map[string]interface{}{
"environment": "test",
"instance_count": 1, // Minimize cost
"instance_class": "t3.micro",
},
// Use mock outputs for dependencies
EnvVars: map[string]string{
"TERRAGRUNT_MOCK_OUTPUTS": "true",
},
}
// Clean up after test
defer terraform.Destroy(t, terraformOptions)
// Deploy
terraform.InitAndApply(t, terraformOptions)
// Get outputs
apiEndpoint := terraform.Output(t, terraformOptions, "api_endpoint")
require.NotEmpty(t, apiEndpoint)
// Test health endpoint
http_helper.HttpGetWithRetry(t,
apiEndpoint+"/health",
nil, // response validator
200,
"healthy",
10,
30*time.Second,
)
// Test that the service returns proper headers
resp, err := http.Get(apiEndpoint + "/health")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
assert.NotEmpty(t, resp.Header.Get("X-Request-Id"))
}Testing generate Blocks
Terragrunt's generate blocks create files on the fly. Test that generated files are correct:
# terragrunt.hcl
generate "backend" {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
contents = <<EOF
terraform {
backend "s3" {
bucket = "${local.state_bucket}"
key = "${path_relative_to_include()}/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "${local.lock_table}"
encrypt = true
}
}
EOF
}#!/bin/bash
# test-generate.sh
# Run terragrunt to generate files
cd environments/dev/services/api
terragrunt terragrunt-info # Triggers generate blocks without applying
# Verify generated backend.tf
if [ ! -f "backend.tf" ]; then
echo "❌ backend.tf was not generated"
exit 1
fi
# Validate content
if ! grep -q "encrypt.*true" backend.tf; then
echo "❌ backend.tf missing encryption config"
exit 1
fi
echo "✅ Generated files look correct"CI Pipeline
# .github/workflows/terragrunt-test.yml
name: Terragrunt Tests
on:
pull_request:
paths: ['environments/**', 'modules/**']
jobs:
validate:
runs-on: ubuntu-latest
strategy:
matrix:
environment: [dev, staging, prod]
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.7.x
- name: Install Terragrunt
run: |
curl -Lo terragrunt https://github.com/gruntwork-io/terragrunt/releases/latest/download/terragrunt_linux_amd64
chmod +x terragrunt
sudo mv terragrunt /usr/local/bin/
- name: Configure AWS credentials (read-only)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.READONLY_ROLE_ARN }}
aws-region: us-east-1
- name: Validate all modules
run: |
cd environments/${{ matrix.environment }}
terragrunt validate-all \
--terragrunt-non-interactive \
--terragrunt-include-external-dependencies
- name: Plan with mock outputs
run: |
cd environments/${{ matrix.environment }}
terragrunt plan-all \
--terragrunt-non-interactive \
--terragrunt-ignore-external-dependencies \
-detailed-exitcode 2>&1 | tee /tmp/plan-${{ matrix.environment }}.txt
EXIT_CODE=${PIPESTATUS[0]}
if [ $EXIT_CODE -eq 1 ]; then
echo "Plan failed"
cat /tmp/plan-${{ matrix.environment }}.txt
exit 1
fiSummary
Terragrunt testing covers a layer that Terratest alone can't reach:
| Pattern | Use Case |
|---|---|
mock_outputs |
Test modules without deploying dependencies |
before_hook |
Validate inputs and prerequisites before apply |
after_hook |
Run smoke tests and notifications after apply |
run_cmd |
Validate external state during config parsing |
validate-all |
Check all modules in an environment quickly |
plan-all --ignore-external-dependencies |
CI plan check without full dependency graph |
The mock_outputs + validate-all + plan-all combination is your fast CI feedback loop — runs in under 2 minutes for most codebases, catches syntax errors and type mismatches, and requires only read-only cloud credentials.
After Terragrunt provisions your infrastructure, HelpMeTest can run continuous end-to-end tests to verify the deployed application actually works — not just that the Terraform apply succeeded.