Skip to content

Terragrunt — keep Terraform config DRY across environments

How Terragrunt removes copy-paste from a multi-environment Terraform tree — repo layout, includes, dependencies, and the run-all pattern we use in production.

A Terraform tree with three environments and twenty modules turns into a copy-paste problem fast: backend config repeated in every directory, provider blocks duplicated, variable values restated, module versions drifting between environments. Terragrunt is a thin wrapper that pushes all of that into includes and locals — the .tf modules stay vanilla, but the per-environment wiring lives in one place. This article covers the repo layout we ship to clients, the include hierarchy, the dependency pattern, and the run-all edge cases that bite.

How to verify

terragrunt --version
terragrunt run-all init --terragrunt-non-interactive
terragrunt run-all plan --terragrunt-non-interactive
terragrunt graph-dependencies
terragrunt render-json --with-metadata > /tmp/render.json
terragrunt hclfmt --terragrunt-check

render-json is the secret weapon: it expands every include, mock, dependency, and local into a single resolved JSON document. When a config “doesn’t do what I think it does,” render-json shows what Terragrunt is actually feeding to Terraform. graph-dependencies shows the DAG that run-all will walk.

What’s happening

Terragrunt is a wrapper. For each terragrunt.hcl file, it (1) reads the includes and merges their contents, (2) resolves dependencies and renders their outputs into inputs, (3) writes a generated backend.tf and provider.tf into the directory, and (4) runs terraform with the resolved inputs. The wrapped terraform sees a perfectly normal-looking module.

The four concepts you live with:

  • include "root". A child terragrunt.hcl inherits backend, provider, and remote-state config from a parent. The parent lives at the repo root; children live in per-environment directories.
  • dependency "vpc". A child can depend on another Terragrunt config and read its outputs. This is how the app stack gets the VPC ID without hardcoding it.
  • mock_outputs. Lets terragrunt plan work when a dependency hasn’t been applied yet — without a mock, the dependency must have real outputs, which it doesn’t on first run.
  • run-all. Applies (or plans, destroys, etc.) every Terragrunt config under the current directory, in dependency order. This is what makes “deploy the whole environment” one command.

The reason Terragrunt exists, in one sentence: Terraform workspaces are not enough — they share provider/backend config but require runtime ceremony per env, and they don’t scope state. Terragrunt gives one state file per leaf directory and one backend block written once.

The procedure

  1. Layout.

    live/
      terragrunt.hcl                       # root config: backend + provider
      _envcommon/
        vpc.hcl                            # shared inputs for the vpc module
        app.hcl                            # shared inputs for the app module
      prod/
        account.hcl
        us-east-1/
          vpc/terragrunt.hcl
          app/terragrunt.hcl
      staging/
        account.hcl
        us-east-1/
          vpc/terragrunt.hcl
          app/terragrunt.hcl
    modules/
      vpc/                                  # vanilla terraform
      app/                                  # vanilla terraform
  2. Root terragrunt.hcl — written once:

    locals {
      account_vars = read_terragrunt_config(find_in_parent_folders("account.hcl"))
    }
    remote_state {
      backend = "s3"
      generate = { path = "backend.tf", if_exists = "overwrite_terragrunt" }
      config = {
        bucket         = "acme-tf-state-${local.account_vars.locals.account_id}"
        key            = "${path_relative_to_include()}/terraform.tfstate"
        region         = "us-east-1"
        encrypt        = true
        dynamodb_table = "acme-tf-locks"
      }
    }
    generate "provider" {
      path = "provider.tf"
      if_exists = "overwrite_terragrunt"
      contents = <<-EOF
        provider "aws" {
          region = "us-east-1"
          allowed_account_ids = ["${local.account_vars.locals.account_id}"]
          default_tags {
            tags = { ManagedBy = "Terraform", Owner = "platform" }
          }
        }
      EOF
    }
  3. Per-environment account.hcl — small file, just identity:

    locals {
      account_id   = "123456789012"
      account_name = "prod"
    }
  4. Leaf terragrunt.hcl for the VPC:

    include "root" { path = find_in_parent_folders() }
    include "envcommon" {
      path = "${dirname(find_in_parent_folders())}/_envcommon/vpc.hcl"
    }
    terraform {
      source = "../../../modules//vpc?ref=v1.4.0"
    }
    inputs = {
      cidr_block = "10.20.0.0/16"
      az_count   = 3
    }
  5. Leaf with a dependency. The app reads VPC outputs:

    include "root" { path = find_in_parent_folders() }
    dependency "vpc" {
      config_path = "../vpc"
      mock_outputs = { vpc_id = "vpc-mock", private_subnets = ["subnet-mock"] }
      mock_outputs_allowed_terraform_commands = ["validate", "plan"]
    }
    terraform {
      source = "../../../modules//app?ref=v2.1.0"
    }
    inputs = {
      vpc_id          = dependency.vpc.outputs.vpc_id
      private_subnets = dependency.vpc.outputs.private_subnets
      image_tag       = "1.42.3"
    }
  6. Run. cd live/prod/us-east-1 && terragrunt run-all apply --terragrunt-non-interactive. Terragrunt walks dependencies, applies VPC first, then app.

  7. Per-module pinning. Each leaf pins source = "...?ref=vX.Y.Z". Promote a module to a new version by editing the leaf and running apply. This is what enables environment-by-environment rollout of module changes.

Operational notes

  • run-all apply with new dependencies. First init may fail because the dependency’s state doesn’t exist yet. terragrunt run-all init once, then apply.
  • Mocks too permissive. mock_outputs_allowed_terraform_commands should never include apply — that lets you apply with fake inputs and create broken infrastructure.
  • generate overwrites on every run. Files like backend.tf are rewritten — don’t hand-edit them, don’t commit them. Add to .gitignore (per-leaf).
  • Module pinning by branch, not tag. ?ref=main means every apply is a moving target. Always pin to a tag or commit hash.
  • prevent_destroy lifecycle inside a run-all destroy. Terragrunt happily walks the DAG and tells Terraform to destroy; Terraform refuses on protected resources, the run errors, the rest of the destroy doesn’t happen. Plan destroys carefully in shared environments.

We use Terragrunt on engagements where the Terraform estate is large enough that DRY matters — typically 30+ stacks across 3+ environments. The repo layout, the _envcommon library, the dependency graph hygiene, and the on-call runbook for “run-all plan failed in the middle” are operated by our team. The shape of that engagement is part of /en/services/managed-operations/, often paired with /en/knowledge-base/atlantis-terraform-pr-automation/ as the PR layer.