โšก
Zero to Platform Architect2026
Phase 2: IaC & Policy-as-Code

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)

  1. 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.
  2. 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 dependency block builds a Directed Acyclic Graph (DAG) across independent state files, pulling outputs dynamically without monolithic state coupling.
  3. Concurrent Multi-Account Operations (run-all): When deploying or updating foundational infrastructure across 50 member accounts, running terraform apply 50 times manually is unacceptable. terragrunt run-all apply executes 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:

  1. Creates an isolated cache directory at .terragrunt-cache/.
  2. Clones the remote Terraform module source specified in the terraform { source = "..." } block.
  3. Evaluates all generate blocks in your Terragrunt configuration and synthesizes real .tf files (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 plan would crash because the VPC state file does not exist yet!
  • The Solution: Terragrunt uses mock_outputs and mock_outputs_allowed_terraform_commands to inject temporary mock data during plan and validate phases, 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 apply across 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 AssumeRole API calls.
  • Resolution: Throttle Terragruntโ€™s concurrency using the --terragrunt-parallelism flag 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:

  1. 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.
  2. Blast Radius Risk: Running terraform workspace select prod followed by an accidental terraform destroy will destroy production infrastructure using the same directory where development was being tested.
  3. 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:

  1. Extract Shared Primitives: Break the circular loop by extracting the shared Security Group into a standalone upstream security module. The execution order becomes strictly linear: the security module provisions first, and then both vpc and eks depend downstream on security without depending on each other.
  2. Inversion of Control: Provision resources with broad parameters, and bind them using companion attachment resources (e.g., using aws_security_group_rule independently from the security group definition).