Andrew Mercer
on this page

Part of the Terraform guide. Terragrunt wraps the same modules, state and language covered there; see multi-environment configuration for how it compares with plain Terraform approaches.

Written against Terragrunt 1.x (1.0 shipped in 2026 with a formal backwards-compatibility promise for all 1.x releases). If you learned Terragrunt on 0.4x–0.6x, read Section 13 — the CLI, root-file naming and several blocks changed.


Table of Contents

  1. What Terragrunt is
  2. The problems it solves
  3. Core concepts and terminology
  4. Installation
  5. Your first unit
  6. Keeping config DRY: include and the root config
  7. Remote state
  8. Generating files: providers, versions, anything
  9. Dependencies between units
  10. Running many units: run --all, the DAG and --filter
  11. Explicit stacks: terragrunt.stack.hcl
  12. Other configuration blocks worth knowing
  13. Migrating from pre-1.0 Terragrunt
  14. Recommended repository layout
  15. CI/CD with GitLab
  16. Performance
  17. Debugging and introspection
  18. Pitfalls and gotchas
  19. When not to use Terragrunt / alternatives
  20. Cheat sheet

1. What Terragrunt is

Terragrunt is a thin orchestration wrapper around OpenTofu or Terraform, written in Go by Gruntwork. It does not replace the IaC engine — every plan and apply is still executed by tofu or terraform. What Terragrunt adds is a layer above root modules:

  • a configuration language (HCL, in terragrunt.hcl files) for how a module should be deployed — which source, which inputs, which backend, which provider config — separate from what the module creates;
  • inheritance and code generation so that boilerplate (backends, providers, common variables) is written once;
  • a dependency graph across many independent state files, so you can deploy an entire environment in the correct order with one command.

Mental model:

            ┌────────────────────────────┐
            │      terragrunt.hcl         │  ← "how to deploy": source, inputs,
            │  (one per deployable unit)  │     backend, deps, hooks
            └─────────────┬──────────────┘
                          │ downloads module, generates backend.tf/provider.tf,
                          │ sets TF_VAR_*, resolves dependency outputs
                          ▼
            ┌────────────────────────────┐
            │  OpenTofu / Terraform       │  ← "what to create": plain modules
            │  init / plan / apply        │
            └────────────────────────────┘

By default Terragrunt calls tofu if it's on the PATH, otherwise terraform. Override with --tf-path / TG_TF_PATH.


2. The problems it solves

Plain Terraform works beautifully for one environment. The pain shows up when you have many environments × many regions × many components.

2.1 Backend configuration can't use variables

The backend block is evaluated before variables exist, so this is illegal:

terraform {
  backend "azurerm" {
    key = "${var.env}/aks.tfstate"   # ❌ not allowed
  }
}

So every root module ends up with a hand-copied backend block, or a pile of -backend-config= flags in a wrapper script. Copy-paste a backend wrong and two components share a state file — one of the most destructive mistakes possible in Terraform.

Terragrunt: define the backend once, compute the state key from the folder path (path_relative_to_include()), and generate backend.tf into every unit.

2.2 Copy-pasted root modules per environment

The usual non-Terragrunt layout:

envs/
  dev/   main.tf  variables.tf  providers.tf  backend.tf  terraform.tfvars
  stage/ main.tf  variables.tf  providers.tf  backend.tf  terraform.tfvars
  prod/  main.tf  variables.tf  providers.tf  backend.tf  terraform.tfvars

main.tf is nearly identical everywhere; the differences live in tfvars. Drift between the copies is inevitable.

Terragrunt: each environment folder contains only a small terragrunt.hcl pointing at a versioned module and the inputs that differ. Promoting a change is bumping ?ref=v1.4.0 → v1.5.0 in dev, then stage, then prod.

2.3 Giant state files (blast radius)

The alternative to copy-paste is one huge root module per environment. That gives you slow plans, lock contention between teams, and a terraform apply that can take out networking while you were changing a DNS record.

Terragrunt: encourages many small, independent state files (a unit per component: vnet, aks, keyvault, dns…). Each has its own state, its own lock, its own blast radius.

2.4 …but small state files need orchestration

Splitting state creates new problems: the AKS unit needs the subnet ID from the VNet unit, and you must apply VNet first. With raw Terraform you'd wire terraform_remote_state data sources by hand and remember the order.

Terragrunt: dependency blocks read outputs from other units and build a DAG; terragrunt run --all -- apply applies everything in dependency order, in parallel where possible, and destroy in reverse.

2.5 Workspaces aren't a good environment boundary

Terraform workspaces share one backend config and one codebase, so dev and prod usually share credentials and a storage account, and it's too easy to apply in the wrong workspace. Most teams (and HashiCorp's own docs) don't recommend CLI workspaces for strong environment isolation. Terragrunt's folder-per-environment layout makes the environment visible in the path you're standing in.

2.6 Everything else around the edges

  • Running scripts before/after commands (hooks).
  • Retrying known-flaky errors automatically.
  • Pinning Terraform/OpenTofu and Terragrunt versions per repo.
  • Assuming a cloud role per environment.
  • Caching providers across dozens of units so init isn't downloading the same 400 MB provider 40 times.

3. Core concepts and terminology

Term Meaning
Unit A directory containing a terragrunt.hcl. The smallest deployable thing: one module instance, one state file.
Stack A collection of units managed together. Implicit = any directory tree containing units. Explicit = defined by a terragrunt.stack.hcl blueprint that generates units.
Root config A shared config file near the top of the repo (conventionally root.hcl) that units include. It is not a unit.
Partial config Any other .hcl file (e.g. env.hcl, region.hcl, _common/aks.hcl) read via include or read_terragrunt_config().
Module / source The OpenTofu/Terraform module a unit deploys, referenced with terraform { source = ... }.
Catalog A repo of reusable modules, units and stack templates that live configs reference.
Run queue / DAG The ordered graph Terragrunt builds from dependency blocks when running across many units.
Infrastructure-live vs. infrastructure-modules The common two-repo pattern: modules (what) are versioned and generic; live (where/how) is mostly terragrunt.hcl files.

4. Installation

# Linux (amd64) — pick the version you want from the GitHub releases page
TG_VERSION="v1.0.0"   # adjust
curl -sLo terragrunt \
  "https://github.com/gruntwork-io/terragrunt/releases/download/${TG_VERSION}/terragrunt_linux_amd64"
chmod +x terragrunt && sudo mv terragrunt /usr/local/bin/

# macOS
brew install terragrunt

# Version managers (recommended for teams)
mise use terragrunt@latest
# or: asdf / tenv (tenv manages tofu, terraform AND terragrunt)

Verify:

terragrunt --version
tofu --version      # or terraform --version

Pin versions in the repo so everyone (and CI) uses the same binaries:

# root.hcl
terragrunt_version_constraint = ">= 1.0, < 2.0"
terraform_version_constraint  = ">= 1.8"    # applies to tofu or terraform, whichever runs

5. Your first unit

Start with a plain module. Nothing Terragrunt-specific in it — this matters: your modules stay pure Terraform and remain usable without Terragrunt.

# modules/resource-group/main.tf
variable "name" {
  type = string
}

variable "location" {
  type = string
}

variable "tags" {
  type    = map(string)
  default = {}
}

resource "azurerm_resource_group" "this" {
  name     = var.name
  location = var.location
  tags     = var.tags
}

output "name" { value = azurerm_resource_group.this.name }
output "id"   { value = azurerm_resource_group.this.id }

Now a unit that deploys it:

# live/dev/canadacentral/rg-app/terragrunt.hcl
terraform {
  source = "../../../../modules//resource-group"
}

inputs = {
  name     = "rg-app-dev"
  location = "canadacentral"
}
cd live/dev/canadacentral/rg-app
terragrunt plan        # shorthand for: terragrunt run -- plan
terragrunt apply

What actually happened:

  1. Terragrunt copied the module into .terragrunt-cache/<hash>/… (a scratch working directory).
  2. It converted inputs into TF_VAR_name / TF_VAR_location environment variables.
  3. It ran tofu init automatically (auto-init), then tofu plan.

The // in sources

../../modules//resource-group — the double slash separates the root of what gets copied from the subdirectory to run in. Everything left of // is copied into the cache, so relative paths inside the module (../shared/…) keep working. Same convention as Terraform's git::…//subdir syntax.

Remote sources (the normal case)

terraform {
  source = "git::https://gitlab.com/acme/infrastructure-modules.git//azure/resource-group?ref=v1.2.0"
}

Always pin ?ref= to a tag. Unpinned sources mean prod silently picks up whatever is on main.

For local iteration on a module without editing the unit:

terragrunt plan --source ../../../../infrastructure-modules//azure/resource-group

Inputs and precedence

inputs become TF_VAR_* env vars, which means:

  • Inputs that the module doesn't declare are silently ignored (unlike -var, which errors). Typos don't fail. Watch for this.
  • An explicit -var or a *.auto.tfvars in the module will override them.
  • Complex types (maps, lists, objects) are JSON-encoded and work fine.

6. Keeping config DRY: include and the root config

6.1 Root config

Create live/root.hcl. Everything common to every unit goes here: backend, provider generation, common inputs.

# live/root.hcl
locals {
  # Walk up from the *unit's* directory to find these files
  env_vars    = read_terragrunt_config(find_in_parent_folders("env.hcl"))
  region_vars = read_terragrunt_config(find_in_parent_folders("region.hcl"))

  environment = local.env_vars.locals.environment
  location    = local.region_vars.locals.location
}

inputs = {
  location = local.location
  tags = {
    environment = local.environment
    managed_by  = "terragrunt"
    repo        = "infrastructure-live"
  }
}
# live/dev/env.hcl
locals {
  environment     = "dev"
  subscription_id = "00000000-0000-0000-0000-000000000000"
}
# live/dev/canadacentral/region.hcl
locals {
  location = "canadacentral"
}

6.2 Units include it

# live/dev/canadacentral/rg-app/terragrunt.hcl
include "root" {
  path = find_in_parent_folders("root.hcl")
}

terraform {
  source = "git::https://gitlab.com/acme/infrastructure-modules.git//azure/resource-group?ref=v1.2.0"
}

inputs = {
  name = "rg-app-dev"
}

Merged inputs: name from the unit, location and tags from root.

6.3 Why root.hcl and not a root terragrunt.hcl?

Historically the root file was also called terragrunt.hcl. That made it look like a unit, so run --all from the repo root would try to run it. The current recommendation is to name it root.hcl (or anything that isn't terragrunt.hcl) and call find_in_parent_folders("root.hcl"). Calling find_in_parent_folders() with no argument (implicitly looking for terragrunt.hcl) is deprecated.

6.4 Multiple includes and the "component" pattern

You can include more than one file. A common pattern is a per-component shared config so that dev/stage/prod AKS units are a few lines each:

# live/_common/aks.hcl
locals {
  env = read_terragrunt_config(find_in_parent_folders("env.hcl")).locals.environment
}

terraform {
  source = "git::https://gitlab.com/acme/infrastructure-modules.git//azure/aks?ref=v3.1.0"
}

dependency "vnet" {
  config_path = "../vnet"
}

inputs = {
  cluster_name   = "aks-${local.env}"
  subnet_id      = dependency.vnet.outputs.aks_subnet_id
  node_count     = 2
  node_vm_size   = "Standard_D4s_v5"
}
# live/prod/canadacentral/aks/terragrunt.hcl
include "root" {
  path = find_in_parent_folders("root.hcl")
}

include "aks" {
  path   = "${dirname(find_in_parent_folders("root.hcl"))}/_common/aks.hcl"
  expose = true       # makes include.aks.locals available here
}

inputs = {
  node_count   = 5                 # prod override
  node_vm_size = "Standard_D8s_v5"
}

6.5 Merge strategies

include "aks" {
  path           = "..."
  merge_strategy = "deep"   # "no_merge" | "shallow" (default) | "deep"
}
  • shallow (default): top-level attributes/blocks in the child replace the parent's. inputs maps are merged key by key at the top level only — a child tags = {...} replaces the parent's whole tags map.
  • deep: nested maps and lists are merged recursively (lists are concatenated). Useful for tags.
  • no_merge: the include is only used for expose'd values; nothing is merged.

6.6 Useful built-in functions

Function What it does
find_in_parent_folders("x.hcl") Walks up from the unit directory and returns the first match's path.
path_relative_to_include() Path of the unit relative to the included (root) file — the classic state-key generator.
path_relative_from_include() The inverse.
get_terragrunt_dir() Absolute dir of the current terragrunt.hcl.
get_repo_root() Root of the git repo.
get_parent_terragrunt_dir() Dir of the included parent file.
read_terragrunt_config(path) Parse another HCL file and access its locals, inputs, etc.
get_env("NAME", "default") Read an environment variable.
run_cmd("--terragrunt-quiet", "cmd", "args") Run a shell command and use its stdout (e.g. fetch a secret). --terragrunt-quiet suppresses printing the value.
sops_decrypt_file(path) Decrypt a SOPS file (works with Azure Key Vault, AWS KMS, GCP KMS, age, PGP).
get_aws_account_id(), get_aws_caller_identity_arn() AWS helpers.

All standard Terraform functions (jsondecode, merge, format, lookup, …) are available too.


7. Remote state

7.1 Backend generation (Azure example)

# live/root.hcl (continued)
remote_state {
  backend = "azurerm"

  generate = {
    path      = "backend.tf"
    if_exists = "overwrite_terragrunt"
  }

  config = {
    subscription_id      = local.env_vars.locals.subscription_id
    resource_group_name  = "rg-tfstate-${local.environment}"
    storage_account_name = "sttfstate${local.environment}acme"
    container_name       = "tfstate"
    key                  = "${path_relative_to_include()}/terraform.tfstate"
    use_azuread_auth     = true
  }
}

For a unit at live/dev/canadacentral/aks, path_relative_to_include() is dev/canadacentral/aks, so the key is dev/canadacentral/aks/terraform.tfstate. The folder path is the state address. This is what kills the shared-state-file copy-paste bug.

Terragrunt writes a backend.tf into the cache dir:

terraform {
  backend "azurerm" {
    container_name       = "tfstate"
    key                  = "dev/canadacentral/aks/terraform.tfstate"
    ...
  }
}

7.2 AWS example

remote_state {
  backend = "s3"
  generate = {
    path      = "backend.tf"
    if_exists = "overwrite_terragrunt"
  }
  config = {
    bucket         = "acme-tfstate-${local.account_name}"
    key            = "${path_relative_to_include()}/terraform.tfstate"
    region         = "ca-central-1"
    encrypt        = true
    use_lockfile   = true          # S3-native locking (newer TF/OpenTofu); or dynamodb_table
  }
}

7.3 Backend bootstrapping

For S3 and GCS, Terragrunt can create the bucket (and lock table) for you, with versioning, encryption and public-access blocks. In current versions this is opt-in:

terragrunt backend bootstrap          # create backend resources for this unit
terragrunt run --all --backend-bootstrap -- plan   # bootstrap as part of a run

For azurerm, Terragrunt does not create the storage account — bootstrap it once yourself (a small standalone Terraform config, the az CLI, or your azure-adm-style tooling), with blob versioning and soft-delete on.

Related backend commands:

terragrunt backend migrate <src-unit> <dst-unit>   # move state when you rename/move a unit folder
terragrunt backend delete                           # delete the state for a unit (careful)

backend migrate matters because moving a unit folder changes its state key. Without migrating, Terragrunt sees an empty state and plans to recreate everything.

7.4 generate vs. -backend-config

Use generate = {...} (as above). The older alternative — a module containing an empty backend "s3" {} block that Terragrunt fills via -backend-config flags — still works, but generation keeps modules backend-agnostic.


8. Generating files

generate blocks write arbitrary files into the working directory before running OpenTofu/Terraform. The classic use is the provider block:

# live/root.hcl (continued)
generate "provider" {
  path      = "provider.tf"
  if_exists = "overwrite_terragrunt"
  contents  = <<-EOF
    provider "azurerm" {
      features {}
      subscription_id = "${local.env_vars.locals.subscription_id}"
    }
  EOF
}

generate "versions" {
  path      = "versions_override.tf"
  if_exists = "overwrite_terragrunt"
  contents  = <<-EOF
    terraform {
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 4.0"
        }
      }
    }
  EOF
}

if_exists options:

Value Behaviour
overwrite_terragrunt Overwrite only if the existing file was generated by Terragrunt (has its signature comment). Safe default.
overwrite Always overwrite.
skip Leave an existing file alone.
error Fail if the file exists.

Tip: naming a generated file *_override.tf uses Terraform's override-file semantics, which lets you patch a third-party module's terraform {} block without forking it.

Generated files can be conditional with disable = !local.some_flag.


9. Dependencies between units

9.1 The dependency block

# live/dev/canadacentral/aks/terragrunt.hcl
include "root" {
  path = find_in_parent_folders("root.hcl")
}

terraform {
  source = "git::https://gitlab.com/acme/infrastructure-modules.git//azure/aks?ref=v3.1.0"
}

dependency "rg" {
  config_path = "../rg-app"
}

dependency "vnet" {
  config_path = "../vnet"

  mock_outputs = {
    aks_subnet_id = "/subscriptions/0000/resourceGroups/mock/providers/Microsoft.Network/virtualNetworks/mock/subnets/mock"
  }
  mock_outputs_allowed_terraform_commands = ["init", "validate", "plan"]
}

inputs = {
  resource_group_name = dependency.rg.outputs.name
  subnet_id           = dependency.vnet.outputs.aks_subnet_id
}

What it does:

  • Reads outputs from the other unit's state (Terragrunt runs output -json there, or reads state directly — see Performance).
  • Adds an edge to the DAG so run --all orders them correctly.
  • If the dependency has never been applied, there are no outputs → error, unless mock outputs are allowed for the current command.

9.2 Mock outputs: use narrowly

Mocks let you plan a whole fresh environment before anything exists. Restrict them to validate/plan (as above) — never let mocks reach apply, or you'll create resources pointing at /subscriptions/0000/....

Other options:

dependency "vnet" {
  config_path                             = "../vnet"
  mock_outputs_merge_strategy_with_state  = "shallow"  # fill in missing outputs with mocks
  skip_outputs                            = true        # ordering only, don't read outputs
}

9.3 Ordering-only dependencies

When unit B must apply after A but doesn't consume outputs:

dependencies {
  paths = ["../keyvault", "../dns-zone"]
}

9.4 Dependency vs. terraform_remote_state

dependency terraform_remote_state
Where Terragrunt config Inside the module
Ordering in run --all Yes No
Mocks for fresh envs Yes No
Couples module to backend layout No Yes

Prefer dependency — it keeps modules generic.


10. Running many units

10.1 run --all

From any directory, operate on every unit beneath it:

cd live/dev
terragrunt run --all -- plan
terragrunt run --all -- apply
terragrunt run --all -- destroy      # reverse dependency order
terragrunt run --all -- output

The -- separates Terragrunt flags from the arguments passed through to OpenTofu/Terraform:

terragrunt run --all --parallelism 4 -- plan -lock-timeout=5m

Behaviour:

  • Builds the DAG from dependency/dependencies blocks, runs independent units concurrently, dependents after their parents.
  • apply in --all mode runs with -auto-approve semantics (you confirm once, up front, for the whole stack — Terragrunt lists the units first). In CI, add --non-interactive.
  • If a unit fails, its dependents are skipped; unrelated units continue (use --fail-fast to stop everything).
  • Dependencies outside the current directory are excluded by default (their outputs are still read, but they're not applied). Include them deliberately with a filter (below).

10.2 The --graph variant

cd live/dev/canadacentral/vnet
terragrunt run --graph -- apply   # apply vnet AND everything that depends on it

Handy after changing a foundational unit.

10.3 Filtering with --filter

--filter is the unified query language that replaced the old --queue-include-dir / --queue-exclude-dir family:

terragrunt run --all --filter './prod/**' -- plan            # path glob
terragrunt run --all --filter '!./prod/**' -- plan           # exclude
terragrunt run --all --filter 'aks' -- plan                  # by unit name
terragrunt run --all --filter 'type=unit' -- plan
terragrunt run --all --filter 'reading=_common/aks.hcl' -- plan   # units that read a file
terragrunt run --all --filter 'vnet...' -- plan              # vnet + everything depending on it
terragrunt run --all --filter '...aks' -- plan               # aks + everything it depends on
terragrunt run --all --filter '{./**}...' -- plan            # include external dependencies
terragrunt run --all --filter '[main...HEAD]' -- plan        # units changed in git since main
terragrunt run --all --filter-affected -- plan               # shorthand for changed units

Multiple --filter flags are a union; | inside one expression chains (intersects) conditions:

terragrunt run --all --filter './prod/** | !./prod/legacy/**' -- plan

The git-based filters are the big win for CI: plan only what a merge request touched (plus its dependents).

You can also commit a .terragrunt-filters file, which is read automatically. Old --queue-* flags still work as aliases in 1.x.

10.4 Other run-queue controls

Flag Purpose
--parallelism N Cap concurrent units (protects API rate limits).
--queue-ignore-errors Keep going regardless of failures.
--queue-ignore-dag-order Run everything concurrently (safe for read-only commands like validate).
--fail-fast Abort the whole run on first failure.
--report-file report.json Write a run report (JSON/CSV) of succeeded/failed/skipped units — great for CI summaries.

10.5 exec — arbitrary commands per unit

terragrunt exec -- tflint                       # run any command in a unit's context
terragrunt exec --all -- tflint                 # ...or across every unit in the stack

exec runs with Terragrunt's computed inputs exposed as TF_VAR_*, so tools like tflint, checkov or a custom script see the same values.


11. Explicit stacks

Implicit stacks (a folder of units) work, but in a large estate each environment folder repeats the same set of units with tiny differences. Explicit stacks (GA since v0.78, central to 1.x) replace that repetition with a single blueprint file.

11.1 The pieces

  1. Catalog units — reusable terragrunt.hcl templates in a catalog repo that read their parameters from values.
  2. A terragrunt.stack.hcl in the live repo listing which units to instantiate, where, and with what values.
  3. terragrunt stack generate expands the blueprint into real unit directories under .terragrunt-stack/.

11.2 Catalog unit

# catalog repo: units/vnet/terragrunt.hcl
include "root" {
  path = find_in_parent_folders("root.hcl")
}

terraform {
  source = "git::https://gitlab.com/acme/infrastructure-modules.git//azure/vnet?ref=${values.version}"
}

inputs = {
  name          = values.name
  address_space = values.address_space
}
# catalog repo: units/aks/terragrunt.hcl
include "root" {
  path = find_in_parent_folders("root.hcl")
}

terraform {
  source = "git::https://gitlab.com/acme/infrastructure-modules.git//azure/aks?ref=${values.version}"
}

dependency "vnet" {
  config_path = values.vnet_path
  mock_outputs = { aks_subnet_id = "mock" }
  mock_outputs_allowed_terraform_commands = ["plan", "validate"]
}

inputs = {
  cluster_name = values.cluster_name
  node_count   = values.node_count
  subnet_id    = dependency.vnet.outputs.aks_subnet_id
}

11.3 The stack file

# live/dev/canadacentral/platform/terragrunt.stack.hcl
locals {
  catalog = "git::https://gitlab.com/acme/infrastructure-catalog.git"
  ref     = "v2.0.0"
}

unit "vnet" {
  source = "${local.catalog}//units/vnet?ref=${local.ref}"
  path   = "vnet"
  values = {
    version       = "v1.4.0"
    name          = "vnet-platform-dev"
    address_space = ["10.10.0.0/16"]
  }
}

unit "aks" {
  source = "${local.catalog}//units/aks?ref=${local.ref}"
  path   = "aks"
  values = {
    version      = "v3.1.0"
    cluster_name = "aks-platform-dev"
    node_count   = 2
    vnet_path    = "../vnet"
  }
}

Prod is the same file with different values. You can go further and put the whole stack in the catalog and reference it with a stack block:

# live/prod/canadacentral/terragrunt.stack.hcl
stack "platform" {
  source = "git::https://gitlab.com/acme/infrastructure-catalog.git//stacks/platform?ref=v2.0.0"
  path   = "platform"
  values = {
    env        = "prod"
    node_count = 5
  }
}

11.4 Working with stacks

terragrunt stack generate            # write units into .terragrunt-stack/
terragrunt stack run -- plan         # generate (if needed) + plan all units
terragrunt stack run -- apply
terragrunt stack output              # aggregated outputs from all units
terragrunt stack clean               # remove generated .terragrunt-stack dirs

run --all also auto-generates stacks it encounters.

Generated layout:

platform/
├── terragrunt.stack.hcl
└── .terragrunt-stack/
    ├── vnet/
    │   ├── terragrunt.hcl
    │   └── terragrunt.values.hcl
    └── aks/
        ├── terragrunt.hcl
        └── terragrunt.values.hcl

Notes:

  • Add .terragrunt-stack/ to .gitignore — it's build output.
  • Set no_dot_terragrunt_stack = true on a unit block to generate it directly beside the stack file instead (useful when migrating an existing implicit stack without changing state keys).
  • Because state keys are derived from path, converting an existing implicit stack to an explicit one changes paths — plan for backend migrate or use no_dot_terragrunt_stack.
  • Newer 1.x releases add include support inside stack files, dependency blocks that target a whole stack directory, and autoinclude blocks for patching catalog units (e.g. adding retry rules) without forking them. Check the release notes for your version before relying on these.

11.5 Implicit vs. explicit — which?

Use implicit stacks when… Use explicit stacks when…
Small estate, few environments Many environments/regions sharing the same shape
Every unit is genuinely different You want "an environment" to be a versioned, reviewable artifact
You want to see every file in the repo You're OK with generation as a build step

They mix freely — an implicit stack can contain explicit ones.


12. Other configuration blocks

12.1 Hooks

terraform {
  source = "..."

  before_hook "fmt_check" {
    commands = ["plan", "apply"]
    execute  = ["tofu", "fmt", "-check", "-recursive"]
  }

  before_hook "tflint" {
    commands = ["plan"]
    execute  = ["tflint", "--minimum-failure-severity=error"]
  }

  after_hook "notify" {
    commands     = ["apply"]
    execute      = ["./scripts/notify.sh"]
    run_on_error = false
  }

  error_hook "page_oncall" {
    commands  = ["apply"]
    execute   = ["./scripts/alert.sh"]
    on_errors = [".*"]
  }
}

Hooks run in the cache working dir; reference scripts with get_terragrunt_dir() or get_repo_root() paths.

12.2 extra_arguments

terraform {
  extra_arguments "common" {
    commands  = ["plan", "apply", "destroy"]
    arguments = ["-lock-timeout=10m"]
    env_vars  = { TF_LOG = "" }
  }

  extra_arguments "tfvars" {
    commands           = get_terraform_commands_that_need_vars()
    optional_var_files = ["${get_terragrunt_dir()}/overrides.tfvars"]
  }
}

12.3 errors — retries and ignores

errors {
  retry "transient_azure" {
    retryable_errors   = [".*RetryableError.*", ".*429 Too Many Requests.*", ".*context deadline exceeded.*"]
    max_attempts       = 3
    sleep_interval_sec = 10
  }

  ignore "known_noise" {
    ignorable_errors = [".*Warning: Deprecated attribute.*"]
    message          = "Ignoring known deprecation warning"
  }
}

(Replaces the older top-level retryable_errors / retry_max_attempts attributes.)

12.4 exclude — conditionally skip units

exclude {
  if      = local.environment == "dev"
  actions = ["apply", "destroy"]   # or ["all"]
  exclude_dependencies = false
}

Replaces the old skip = true attribute. Good for "this unit exists only in prod" or "never destroy this from --all".

Also useful in prod:

prevent_destroy = true   # refuse `destroy` on this unit

12.5 Feature flags

feature "enable_private_cluster" {
  default = false
}

inputs = {
  private_cluster_enabled = feature.enable_private_cluster.value
}
terragrunt run --all --feature enable_private_cluster=true -- plan
# or TG_FEATURE="enable_private_cluster=true"

12.6 Cloud auth

AWS has first-class role assumption:

iam_role = "arn:aws:iam::123456789012:role/terragrunt"
# or the newer assume-role via OIDC in CI: --iam-assume-role-web-identity-token

Azure doesn't have an equivalent block — rely on standard ARM_* env vars, workload identity federation (OIDC) in CI, or az login locally, plus subscription_id in the generated provider.

12.7 Secrets

Don't put secrets in inputs literals. Options:

locals {
  secrets = yamldecode(sops_decrypt_file("${get_terragrunt_dir()}/secrets.enc.yaml"))
  db_pass = run_cmd("--terragrunt-quiet", "az", "keyvault", "secret", "show",
                    "--vault-name", "kv-ops", "--name", "db-pass", "--query", "value", "-o", "tsv")
}

Remember: anything passed as an input can still land in state if the module stores it. Better still, have the module read secrets via a data source itself.


13. Migrating from pre-1.0 Terragrunt

The road to 1.0 restructured the CLI. Most old forms emit deprecation warnings; plan to clean them up.

Old New
terragrunt run-all plan terragrunt run --all -- plan
terragrunt graph apply style commands terragrunt run --graph -- apply
terragrunt plan (still works) shorthand for terragrunt run -- plan
--terragrunt-non-interactive, --terragrunt-source, … --non-interactive, --source, … (no terragrunt- prefix)
TERRAGRUNT_* env vars TG_* env vars
--terragrunt-include-dir / --queue-include-dir --filter './path'
--terragrunt-exclude-dir / --queue-exclude-dir --filter '!./path'
--terragrunt-modules-that-include / --units-that-include --filter 'reading=file.hcl'
--queue-strict-include No longer needed (now default)
Root terragrunt.hcl + find_in_parent_folders() root.hcl + find_in_parent_folders("root.hcl")
skip = true exclude { if = true, actions = ["all"] }
retryable_errors = [...] errors { retry "x" { ... } }
Auto-creating S3/GCS backends silently Opt-in: --backend-bootstrap or terragrunt backend bootstrap
terragrunt-info, output-module-groups, graph-dependencies, hclfmt, validate-inputs info print, find/list, dag graph, hcl fmt, hcl validate --inputs

Strategy: upgrade to the latest 0.9x first, run with --strict-mode to turn every deprecation into an error, fix them, then move to 1.x. Since 1.0, Gruntwork commits that existing terragrunt.hcl, terragrunt.stack.hcl and included .hcl files won't need edits within 1.x.


14.1 Two repos

infrastructure-modules/          # (or a "catalog")  — versioned with tags
├── azure/
│   ├── resource-group/
│   ├── vnet/
│   ├── aks/
│   └── keyvault/
├── units/                       # catalog units (for explicit stacks)
└── stacks/                      # catalog stacks

infrastructure-live/             # what's deployed where
├── root.hcl
├── _common/
│   ├── aks.hcl
│   └── vnet.hcl
├── dev/
│   ├── env.hcl
│   └── canadacentral/
│       ├── region.hcl
│       ├── rg-app/terragrunt.hcl
│       ├── vnet/terragrunt.hcl
│       └── aks/terragrunt.hcl
├── stage/ ...
└── prod/
    ├── env.hcl
    ├── canadacentral/ ...
    └── canadaeast/ ...

Hierarchy: account/subscription → environment → region → component. Each level's .hcl contributes locals; root.hcl stitches them together.

14.2 Why separate repos?

  • Modules get semver tags; live configs pin them. A module change is tested once then promoted by bumping a ref per environment — changes to prod are explicit diffs.
  • Different review rules: module repo = code review; live repo = change management.

A monorepo with relative source paths works for small teams, but you lose per-environment version pinning — every environment always runs the current commit.

14.3 .gitignore

.terragrunt-cache/
.terragrunt-stack/
.terraform/
*.tfplan
# Commit .terraform.lock.hcl per unit if you want reproducible provider versions

15. CI/CD with GitLab

A practical pipeline: plan changed units on MRs, apply on merge to main, with manual gates for prod.

# .gitlab-ci.yml
variables:
  TG_NON_INTERACTIVE: "true"
  TG_PROVIDER_CACHE: "1"
  TG_TF_PATH: "tofu"
  # Azure workload identity federation (OIDC) — no client secret
  ARM_USE_OIDC: "true"
  ARM_CLIENT_ID: $AZURE_CLIENT_ID
  ARM_TENANT_ID: $AZURE_TENANT_ID

default:
  image: registry.gitlab.com/acme/images/terragrunt:1.0   # tofu + terragrunt + tflint baked in
  id_tokens:
    ARM_OIDC_TOKEN:
      aud: api://AzureADTokenExchange
  cache:
    key: tg-providers
    paths: [.tg-provider-cache/]

stages: [validate, plan, apply]

fmt:
  stage: validate
  script:
    - terragrunt hcl fmt --check
    - terragrunt hcl validate --inputs

plan:mr:
  stage: plan
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  script:
    - git fetch origin $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
    - >
      terragrunt run --all
      --filter "[origin/${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}...HEAD]"
      --report-file plan-report.json
      -- plan -out=tfplan
  artifacts:
    paths: [plan-report.json, "**/.terragrunt-cache/**/tfplan"]
    expire_in: 1 week

.apply_env:
  stage: apply
  script:
    - cd live/$ENV
    - terragrunt run --all --filter "[HEAD~1...HEAD]" -- apply
  resource_group: $ENV          # GitLab serializes jobs per environment

apply:dev:
  extends: .apply_env
  variables: { ENV: dev }
  environment: dev
  rules:
    - if: $CI_COMMIT_BRANCH == "main"

apply:prod:
  extends: .apply_env
  variables: { ENV: prod }
  environment: prod
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      when: manual

Guidance:

  • Plan what changed: git-based --filter keeps MR pipelines fast and the plan output readable.
  • Changed shared files: a change to root.hcl or _common/aks.hcl affects units that didn't change on disk. Combine with --filter 'reading=_common/aks.hcl' (or run a full plan when root files change).
  • Serialize applies per environment with GitLab resource_group to avoid state lock fights.
  • Separate identities per environment (federated credential per GitLab environment) — prod credentials should be unavailable to dev jobs.
  • Saved plans: -out=tfplan lives in each unit's cache dir. Applying saved plans across jobs requires shipping the cache dirs as artifacts, which gets heavy; many teams re-plan at apply time and rely on review + resource_group serialization instead. Pick one deliberately.
  • Gruntwork sells Terragrunt Scale/Pipelines (PR plans, apply on merge, drift detection, patching), with a free tier since 1.0. Atlantis, Digger, Spacelift, env0 and Scalr also support Terragrunt.

16. Performance

Large estates (hundreds of units) can be slow. Main levers:

  1. Provider cache — --provider-cache / TG_PROVIDER_CACHE=1 runs a local provider cache server so each provider version is downloaded once for the whole run. With OpenTofu 1.10+, Terragrunt can also use OpenTofu's native cross-process provider cache automatically.
  2. Read dependency outputs from state directly — the dependency-fetch-output-from-state experiment/flag reads outputs straight from the backend (S3) instead of running init + output in every dependency. Check current docs for your backend.
  3. Avoid deep dependency fan-in — a unit with 15 dependencies runs 15 output fetches every time.
  4. --parallelism — raise it for read-only commands, lower it if you hit cloud API throttling.
  5. Filter aggressively — don't run --all across the whole repo when you mean one environment.
  6. Keep run_cmd cheap — it executes on every config parse (and configs are parsed multiple times during discovery). Cache expensive lookups or move them into the module.

17. Debugging and introspection

terragrunt render --format json        # fully-resolved config for a unit (includes merged, locals evaluated)
terragrunt info print                   # paths, working dir, download dir for the unit
terragrunt find --dag                   # discover units, in dependency order
terragrunt list --tree                  # tree view of units/stacks
terragrunt dag graph | dot -Tsvg > dag.svg   # dependency graph
terragrunt hcl validate --inputs        # flag inputs the module doesn't declare (catches typos!)
terragrunt --log-level debug plan       # verbose logging
terragrunt --inputs-debug plan          # writes terragrunt-debug.tfvars.json for inspection

hcl validate --inputs is worth running in CI — it fixes the "unknown input silently ignored" problem from Section 5.

To poke at the actual working directory:

cd "$(terragrunt info print | jq -r .WorkingDir)"
ls   # see generated backend.tf / provider.tf alongside the module

18. Pitfalls and gotchas

  1. Moving or renaming unit folders changes state keys. Use terragrunt backend migrate (or tofu state + manual copy) before applying, or you'll get a plan to recreate everything.
  2. Silent unknown inputs. Typos in inputs are ignored. Run hcl validate --inputs.
  3. Mock outputs leaking into apply. Always set mock_outputs_allowed_terraform_commands.
  4. run --all -- apply on prod from a laptop. It's one confirmation for N units. Use prevent_destroy, exclude blocks, CI-only prod credentials, and filters.
  5. run --all -- destroy follows dependencies outward, including dependents you may not have meant. Read the unit list it prints before confirming.
  6. Stale .terragrunt-cache. Rarely, a cached download misbehaves — delete the folder (find . -type d -name .terragrunt-cache -prune -exec rm -rf {} +).
  7. Plans of dependent units can be wrong before the parent applies. A plan for AKS uses the VNet's current outputs; if the VNet change in the same MR will alter those outputs, the AKS plan is out of date. Expect a second pass.
  8. Shallow merge surprises. A child tags = {...} wipes the root's tags unless you use merge_strategy = "deep" or merge explicitly with merge() in the child.
  9. find_in_parent_folders starts from the unit, even when called inside an included file. That's usually what you want, but it surprises people writing _common files.
  10. Too many tiny units. Splitting every resource into its own unit gives you a slow, fragile DAG. Group by lifecycle and ownership (networking, cluster, cluster add-ons, app infra), not by resource type.
  11. Explicit stack migration changes paths → state keys. Use no_dot_terragrunt_stack or migrate state.

19. When not to use Terragrunt

Terragrunt shines with multi-environment, multi-region, multi-team estates. It's probably overkill when:

  • You have one or two environments and a handful of root modules — plain Terraform + a -backend-config file per env is fine.
  • You're all-in on HCP Terraform / Terraform Enterprise, whose workspaces, variable sets, run triggers and (newer) Terraform Stacks cover much of the same ground natively. HCP Terraform Stacks require HCP; they don't run with the open-source CLI alone.
  • Your team doesn't want another layer of HCL and another tool to learn.

Alternatives and adjacent tools:

Tool Approach
Plain Terraform/OpenTofu + wrapper scripts/Makefile Simple, but you rebuild DRY backends and ordering yourself.
OpenTofu early variable evaluation Since OpenTofu 1.8, variables/locals can be used in backend and module source blocks — removes one of Terragrunt's original reasons to exist (for OpenTofu users), but not the orchestration/DAG parts.
Terramate Stack orchestration and code generation; works with plain Terraform; strong change detection.
Atmos (Cloud Posse) YAML-driven stack configuration with deep inheritance.
HCP Terraform Stacks Native multi-component deployments, HCP-only.
CDKTF / Pulumi General-purpose languages instead of HCL. (CDKTF has been deprecated by HashiCorp; check status before adopting.)

20. Cheat sheet

# Single unit
terragrunt plan                                 # = terragrunt run -- plan
terragrunt apply
terragrunt run -- state list
terragrunt run -- import azurerm_resource_group.this /subscriptions/.../resourceGroups/rg-app-dev
terragrunt plan --source ../../modules//aks     # test local module changes

# Many units
terragrunt run --all -- plan
terragrunt run --all --non-interactive -- apply
terragrunt run --all --filter './prod/**' -- plan
terragrunt run --all --filter-affected -- plan
terragrunt run --all --filter 'vnet...' -- plan
terragrunt run --graph -- apply

# Stacks
terragrunt stack generate
terragrunt stack run -- plan
terragrunt stack output
terragrunt stack clean

# Backend
terragrunt backend bootstrap
terragrunt backend migrate old/path new/path

# Introspection & hygiene
terragrunt render --format json
terragrunt find --dag
terragrunt dag graph
terragrunt hcl fmt
terragrunt hcl validate --inputs
terragrunt --log-level debug plan

Minimal unit template:

include "root" {
  path = find_in_parent_folders("root.hcl")
}

terraform {
  source = "git::https://gitlab.com/acme/infrastructure-modules.git//azure/COMPONENT?ref=vX.Y.Z"
}

dependency "upstream" {
  config_path                             = "../upstream"
  mock_outputs                            = { id = "mock" }
  mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}

inputs = {
  upstream_id = dependency.upstream.outputs.id
}

References