Lesson 3: Terragrunt & Multi-Environment Fleet Orchestration
๐ง The Concept (Explain Like Iโm 5)
Imagine you manage a national franchise of 50 restaurants across the country:
- The Pure Terraform Approach (Copy-Paste Hell): In every single restaurantโs office, you write out the exact same 20-page employee manual by hand: the health inspection rules, the cash register instructions, the trash disposal procedures, and the emergency exits. If the company updates its emergency exit policy, you must travel to all 50 restaurants and manually edit 50 individual manuals.
- The Terragrunt Approach (DRY Master Blueprint): You write one centralized Master Corporate Handbook at headquarters. Each local restaurant only receives a single 1-page form containing its unique local details: restaurant address, manager name, and seating capacity.
Terragrunt is a thin, open-source orchestration wrapper for Terraform that enforces the DRY (Donโt Repeat Yourself) principle:
- You define your remote S3 backend, DynamoDB locks, AWS providers, and default tags exactly once in a root file.
- Each child environment (Dev, Staging, Prod across 50 AWS accounts) simply specifies a minimal list of input variables.
๐ข The Enterprise Context (Why Platform Architects Care)
- Fleet-Scale State File Management: In large enterprises, infrastructure is partitioned across dozens of AWS accounts (Network Hub, Security, Shared Services, Dev, Staging, Prod). Pure Terraform requires duplicating backend blocks and provider declarations in hundreds of folders. Terragrunt generates these dynamically.
- Deterministic Cross-Module Dependency Trees: Pure Terraform struggles when Module B requires outputs from Module A before Module A has been provisioned. Terragruntโs native
dependencyblock builds a Directed Acyclic Graph (DAG) across independent state files, pulling outputs dynamically without monolithic state coupling. - Concurrent Multi-Account Operations (
run-all): When deploying or updating foundational infrastructure across 50 member accounts, runningterraform apply50 times manually is unacceptable.terragrunt run-all applyexecutes across hundreds of isolated state files concurrently, automatically honoring topological dependency ordering.
๐บ๏ธ Visual Architecture: Enterprise Terragrunt Hierarchy & Execution DAG
flowchart TD
subgraph RootLevel ["Repository Root (/infrastructure)"]
RootHCL["<b>root terragrunt.hcl</b><br/>โข Generates remote S3 backend dynamically<br/>โข Generates cross-account AWS provider with AssumeRole<br/>โข Enforces mandatory tags & KMS encryption"]
end
subgraph DevAccount ["Dev Account (111111111111)"]
DevVPC["<b>dev/us-east-1/vpc</b><br/>(inputs: 10.10.0.0/16)"]
DevEKS["<b>dev/us-east-1/eks</b><br/>(dependency: vpc)"]
DevRDS["<b>dev/us-east-1/rds</b><br/>(dependency: vpc, eks)"]
end
subgraph ProdAccount ["Prod Account (999999999999)"]
ProdVPC["<b>prod/us-east-1/vpc</b><br/>(inputs: 10.20.0.0/16)"]
ProdEKS["<b>prod/us-east-1/eks</b><br/>(dependency: vpc)"]
ProdRDS["<b>prod/us-east-1/rds</b><br/>(dependency: vpc, eks)"]
end
RootHCL -.->|"Dynamically inherited by"| DevVPC
RootHCL -.->|"Dynamically inherited by"| DevEKS
RootHCL -.->|"Dynamically inherited by"| ProdVPC
RootHCL -.->|"Dynamically inherited by"| ProdEKS
DevVPC -->|"Output: vpc_id & subnets"| DevEKS
DevVPC -->|"Output: db_subnet_group"| DevRDS
DevEKS -->|"Output: cluster_sg_id"| DevRDS
ProdVPC -->|"Output: vpc_id & subnets"| ProdEKS
ProdVPC -->|"Output: db_subnet_group"| ProdRDS
ProdEKS -->|"Output: cluster_sg_id"| ProdRDS
๐ฌ Under the Hood: Dynamic Code Generation & Dependency Resolution
1. Dynamic File Generation (generate blocks)
When you execute terragrunt apply, Terragrunt does not run directly in your source folder. It:
- Creates an isolated cache directory at
.terragrunt-cache/. - Clones the remote Terraform module source specified in the
terraform { source = "..." }block. - Evaluates all
generateblocks in your Terragrunt configuration and synthesizes real.tffiles (backend.tf,provider.tf) directly into the cache folder before invoking the Terraform CLI.
flowchart LR
Source["Terragrunt Config<br/>(terragrunt.hcl)"] --> Engine["Terragrunt Pre-Processor"]
GitMod["Remote Git Module<br/>(terraform-aws-eks:v3.2.0)"] --> Cache[".terragrunt-cache/"]
Engine -->|"Generates backend.tf & provider.tf"| Cache
Engine -->|"Injects inputs as TF_VARs"| Cache
Cache --> TFBin["Terraform Binary Engine<br/>(terraform apply)"]
2. Dependency Resolution Engine & mock_outputs
When Module B declares dependency "vpc" { config_path = "../vpc" }:
- Terragrunt navigates to
../vpc, reads its remote state backend configuration, and fetches its outputs directly from AWS S3. - The Greenfield Chicken-and-Egg Problem: In a brand-new environment, running
terragrunt run-all planwould crash because the VPC state file does not exist yet! - The Solution: Terragrunt uses
mock_outputsandmock_outputs_allowed_terraform_commandsto inject temporary mock data duringplanandvalidatephases, allowing full-stack planning before resources are created:
dependency "vpc" {
config_path = "../vpc"
mock_outputs = {
vpc_id = "vpc-00000000000000000"
private_subnet_ids = ["subnet-00000001", "subnet-00000002"]
}
mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}
๐ป Production Implementation: Multi-Account Fleet Structure
1. Repository Directory Layout
infrastructure-fleet/
โโโ terragrunt.hcl # Root configuration (Backend & Provider generation)
โโโ environments/
โ โโโ dev/
โ โ โโโ account.hcl # Account ID: 111111111111
โ โ โโโ us-east-1/
โ โ โโโ region.hcl # Region: us-east-1
โ โ โโโ vpc/
โ โ โ โโโ terragrunt.hcl # Provisions VPC
โ โ โโโ eks/
โ โ โโโ terragrunt.hcl # Provisions EKS
โ โโโ prod/
โ โโโ account.hcl # Account ID: 999999999999
โ โโโ us-east-1/
โ โโโ region.hcl # Region: us-east-1
โ โโโ vpc/
โ โ โโโ terragrunt.hcl # Provisions VPC
โ โโโ eks/
โ โโโ terragrunt.hcl # Provisions EKS
2. Root Configuration (/infrastructure-fleet/terragrunt.hcl)
locals {
# Dynamically discover variables from parent directories
account_vars = read_terragrunt_config(find_in_parent_folders("account.hcl"))
region_vars = read_terragrunt_config(find_in_parent_folders("region.hcl"))
account_id = local.account_vars.locals.aws_account_id
account_name = local.account_vars.locals.account_name
aws_region = local.region_vars.locals.aws_region
}
# 1. Automatically generate remote S3 backend with dynamic key pathing
remote_state {
backend = "s3"
config = {
encrypt = true
bucket = "corp-platform-tfstate-${local.account_id}-${local.aws_region}"
key = "${path_relative_to_include()}/terraform.tfstate"
region = local.aws_region
dynamodb_table = "corp-platform-tfstate-locks"
}
generate = {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
}
# 2. Automatically generate AWS Provider block with Cross-Account IAM Role Assumption
generate "provider" {
path = "provider.tf"
if_exists = "overwrite_terragrunt"
contents = <<EOF
provider "aws" {
region = "${local.aws_region}"
assume_role {
role_arn = "arn:aws:iam::${local.account_id}:role/PlatformDeployerRole"
session_name = "TerragruntFleetDeployment"
}
default_tags {
tags = {
Environment = "${local.account_name}"
ManagedBy = "Terragrunt"
CostCenter = "CoreInfrastructure"
}
}
}
EOF
}
3. Child EKS Configuration (/environments/prod/us-east-1/eks/terragrunt.hcl)
include "root" {
path = find_in_parent_folders()
}
terraform {
source = "git::git@github.com:corp/terraform-aws-eks.git?ref=v4.1.0"
}
# Resolve VPC dependency dynamically
dependency "vpc" {
config_path = "../vpc"
mock_outputs = {
vpc_id = "vpc-mock-00000000"
private_subnet_ids = ["subnet-mock-1", "subnet-mock-2", "subnet-mock-3"]
}
mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}
inputs = {
cluster_name = "prod-workloads-eks"
cluster_version = "1.30"
vpc_id = dependency.vpc.outputs.vpc_id
subnet_ids = dependency.vpc.outputs.private_subnet_ids
managed_node_groups = {
general = {
instance_types = ["m6i.xlarge"]
min_size = 3
max_size = 12
desired_size = 3
}
}
}
๐ ๏ธ Step-by-Step CLI Command Playbook
# 1. Plan all modules across the production account honoring the dependency DAG
cd /environments/prod
terragrunt run-all plan --terragrunt-parallelism 4
# 2. Deploy specific module and automatically apply any unapplied upstream dependencies
cd /environments/prod/us-east-1/eks
terragrunt apply
# 3. Output visual dependency graph of modules in Graphviz DOT format
terragrunt graph-dependencies | dot -Tpng -o dependencies.png
# 4. Clean all temporary Terragrunt cache directories across the repository
find . -type d -name ".terragrunt-cache" -prune -exec rm -rf {} +
โ ๏ธ Real-World Failure Modes & Troubleshooting Playbook
Scenario 1: AWS STS AssumeRole Throttling During run-all
- Symptom: Running
terragrunt run-all applyacross 40 accounts fails with:Error assuming role: Throttling: Rate exceeded - Root Cause: By default, Terragrunt spins up unlimited concurrent threads for independent modules, bombarding AWS Security Token Service (STS) with hundreds of simultaneous
AssumeRoleAPI calls. - Resolution: Throttle Terragruntโs concurrency using the
--terragrunt-parallelismflag and configure exponential backoff in AWS SDK:terragrunt run-all apply --terragrunt-parallelism 5
Scenario 2: Stale Module Cache in .terragrunt-cache
- Symptom: You push a critical hotfix to your moduleโs Git tag (
v4.1.0), but Terragrunt continues running the old buggy code. - Root Cause: Terragrunt caches cloned module repositories inside
.terragrunt-cache/to speed up local execution. If the tag was overwritten or commit changed, the cache may not invalidate automatically. - Resolution: Purge cache or pass the download flag:
terragrunt apply --terragrunt-download-dir /tmp/fresh-cache # Or purge locally: rm -rf .terragrunt-cache
๐ Staff Architect & SRE Interview Scenarios
โ Question 1: Terragrunt vs. Terraform Workspaces
Question: Why do enterprise platform teams strongly prefer Terragruntโs directory-based separation over Terraform Workspaces for managing multi-account environments (Dev, Staging, Prod)?
Answer: Terraform Workspaces share the exact same underlying Terraform code and backend configuration, switching only the state key. This creates severe enterprise vulnerabilities:
- Lack of Account Boundary Isolation: Workspaces cannot natively switch AWS IAM roles or target different AWS accounts dynamically without complex conditional logic inside the code.
- Blast Radius Risk: Running
terraform workspace select prodfollowed by an accidentalterraform destroywill destroy production infrastructure using the same directory where development was being tested. - Configuration Drift Inflexibility: In the real world, Production frequently requires configurations that Development does not need (e.g. multi-AZ replication, Transit Gateway attachments, enterprise KMS keys). Directory-based Terragrunt allows explicit, auditable variable inputs per environment while maintaining DRY backend governance.
โ Question 2: What is a Circular Dependency in Terragrunt and How Do You Resolve It?
Question: If Module A (VPC) needs the Security Group ID from Module B (EKS), but Module B needs the Subnet IDs from Module A, Terragrunt halts with a cyclic dependency error. How do you resolve this architecturally?
Answer: Circular dependencies are a sign of improper module boundaries. To resolve this:
- Extract Shared Primitives: Break the circular loop by extracting the shared Security Group into a standalone upstream
securitymodule. The execution order becomes strictly linear: thesecuritymodule provisions first, and then bothvpcandeksdepend downstream onsecuritywithout depending on each other. - Inversion of Control: Provision resources with broad parameters, and bind them using companion attachment resources (e.g., using
aws_security_group_ruleindependently from the security group definition).