This lesson closes module 7 and pays off module 6's last outstanding debt. When in 06-01 we compared the four separation strategies, the last column of the table was Terragrunt, with a note: «the answer to the question left open when EcoMarket went from three environments to twelve». And in 07-01, the decision tree ended in a yellow box saying «Terragrunt: 07-05».
The open question is specific and deserves careful phrasing, because the whole lesson depends on it:
The strategies in 07-01 work well up to a certain size. One directory per environment is clean with three environments and duplicates scaffolding with twelve. Layers with independent states contain the blast radius and add an order of application that somebody has to remember. What do you do when both happen at once?
Terragrunt is one answer to that question. It is not the only one, and it is not always the right one. This lesson presents it honestly: what it solves, what it does not solve, what it costs, what alternatives exist and how to migrate an existing repository without touching a single state file.
And I will give the recommendation up front, because I would rather you had it in mind while you read the rest: if directories and .tfvars files are enough for you, do not adopt it. Terragrunt is one more layer of indirection, and layers of indirection are paid for every day.
- The problem at scale: from 3 environments to 12
EcoMarket opens in France, Italy and Germany. The platform is now deployed in four regions (eu-west-1, eu-west-3, eu-south-1, eu-central-1), each with its three environments. That is twelve combinations, plus the per-pull-request ephemeral ones from 06-01. And each combination has three components with separate states — network, data, app, following strategy 3 from 07-01.
36 root configurations. That is the number to keep in mind for the rest of the lesson.
The four symptoms are not hypothetical: they are the ones that literally appear in a repository like that.
Symptom 1: the backend.tf that drifts out of sync
# live/eu-west-1/prod/data/backend.tf
terraform {
backend "s3" {
bucket = "ecomarket-tfstate-123456789014"
key = "ecomarket/prod/data/terraform.tfstate"
region = "eu-west-1"
encrypt = true
use_lockfile = true
}
}That file, or one almost identical to it, exists 36 times. And each copy has three fields that vary and four that do not. The day kms_key_id has to be added because security requires a customer-managed key (07-04), that is 36 edits in a PR nobody really reviews.
And the worst part is not the mass edit, it is the silent error:
# live/eu-central-1/staging/data/backend.tf
terraform {
backend "s3" {
bucket = "ecomarket-tfstate-123456789013"
key = "ecomarket/staging/data/terraform.tfstate" # ← the region is missing
region = "eu-central-1"
}
}Somebody copied the eu-west-1 directory and forgot to include the region in the key. The result: two regions share the same state file. The first apply in Frankfurt sees Ireland's resources as «existing» and proposes destroying them, because they are not in this region's code. It is not a theoretical error: it is exactly the kind of accident a hand-copied backend.tf produces, and there is no check that would catch it before the plan.
Symptom 2: the copied provider and required_providers
# The same pair of files, 36 times.
provider "aws" {
region = "eu-west-1"
assume_role {
role_arn = "arn:aws:iam::123456789014:role/ecomarket-terraform-prod"
}
default_tags { tags = { Project = "ecomarket", Environment = "prod", ManagedBy = "terraform" } }
}
terraform {
required_version = "~> 1.9"
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.60" }
random = { source = "hashicorp/random", version = "~> 3.6" }
}
}Bumping the AWS provider version is 36 more edits plus 36 lock files. And here a consequence appears that people do not anticipate: it is so laborious that it stops being done, the repository accumulates different versions in different places, and the day somebody unifies them they get a plan with unexpected changes in half the environments.
Symptom 3: the repeated terraform_remote_state blocks
# live/eu-west-1/prod/app/data.tf — and its twin in the other 11 places
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "ecomarket-tfstate-123456789014"
key = "ecomarket/prod/network/terraform.tfstate"
region = "eu-west-1"
}
}
data "terraform_remote_state" "data" {
backend = "s3"
config = {
bucket = "ecomarket-tfstate-123456789014"
key = "ecomarket/prod/data/terraform.tfstate"
region = "eu-west-1"
}
}Each app repeats the backend configuration of its two dependencies. Twelve times, with two blocks each: 24 places where a mistyped key produces a plan that reads the wrong state or fails with an uninformative error.
Symptom 4: the apply order somebody remembers
# The deployment "procedure" for a new region.
# It lives in a document, or in the head of whoever did it last time.
cd live/eu-central-1/prod/network && terraform init -reconfigure && terraform apply
cd ../data && terraform init -reconfigure && terraform apply
cd ../app && terraform init -reconfigure && terraform applyWith three components it is manageable. With six — add observability, dns and cdn — and four regions, it is a 24-step manual procedure in an order Terraform does not know about and cannot verify. And the failure is unpleasant: applying app before network does not give a clear error but a terraform_remote_state that returns an empty state and a message about a non-existent key in a map.
The shape of the problem
flowchart TD
subgraph TODAY["Today: 36 roots, each with everything"]
direction LR
A1["network/<br/>backend.tf ✕36<br/>providers.tf ✕36<br/>versions.tf ✕36"]
A2["data/<br/>+ remote_state<br/>of network"]
A3["app/<br/>+ remote_state<br/>of network and data"]
end
subgraph WITH["With Terragrunt: the common part once"]
direction LR
B0["_envcommon/<br/>+ root terragrunt.hcl<br/>backend and provider GENERATED"]
B1["network/terragrunt.hcl<br/>~10 lines"]
B2["data/terragrunt.hcl<br/>dependency network"]
B3["app/terragrunt.hcl<br/>dependency network, data"]
B0 -.-> B1
B0 -.-> B2
B0 -.-> B3
end
TODAY -->|"the 06-01 question"| WITH
style TODAY fill:#fee2e2,stroke:#b91c1c
style WITH fill:#dcfce7,stroke:#15803d
The four symptoms share one root cause: what varies between the 36 roots is little, and what repeats is a lot. Terragrunt exists to invert that ratio.
- What Terragrunt is and what it is not
Terragrunt is a thin wrapper around the Terraform CLI. It is a Gruntwork binary that reads terragrunt.hcl files, generates the repetitive configuration, resolves dependencies between components and then invokes terraform with the right arguments.
| Terragrunt is not | Why the distinction matters |
|---|---|
| A replacement for Terraform | It needs the terraform (or opentofu) binary installed. It only wraps it |
| A new language | It uses HCL, the one you have known since module 2 |
| A provider or a state engine | The state is still managed by Terraform, in the same backend |
| A module manager | Modules are still Terraform modules, versioned the same way (04-05) |
| A security layer | Everything from 07-04 still applies unchanged |
Something that changes your .tf files |
The modules you wrote in module 4 are used as they are, without touching a line |
That last row is the most important and the one that makes it worth trying: adopting Terragrunt does not require changing the Terraform code. It changes how it is invoked, not what is invoked.
What Terragrunt does do, in one sentence: it turns each root configuration into a ten-line file that says which module to use, with what inputs, and which other components it depends on; and it generates everything else by convention.
sequenceDiagram
participant U as You
participant TG as Terragrunt
participant FS as Temporary directory<br/>.terragrunt-cache/
participant TF as terraform
U->>TG: terragrunt apply
TG->>TG: Read terragrunt.hcl + the parent includes
TG->>FS: Download the `source` module
TG->>FS: GENERATE backend.tf and provider.tf
TG->>TG: Resolve the `dependency` blocks:<br/>read other components' outputs
TG->>TF: terraform init -backend-config=...
TG->>TF: terraform apply -var-file=... (inputs via TF_VAR_)
TF-->>U: The usual plan and result
The temporary-directory step explains several oddities you will see later: Terragrunt does not run Terraform in your directory, but in a copy under .terragrunt-cache/. That is where the generated backend.tf, the downloaded module and the .terraform/ directory appear. That is why that directory goes into the .gitignore (07-02 §3) and why error messages sometimes point at paths you do not recognise.
- Terragrunt, OpenTofu and the licensing context
It deserves a short section because it changes real decisions.
In August 2023 HashiCorp changed Terraform's licence from MPL 2.0 to the BSL (Business Source License). In response, the Linux Foundation took in OpenTofu, a fork of Terraform 1.5.x under the MPL, which has followed its own development since.
| Aspect | Terraform | OpenTofu |
|---|---|---|
| Licence | BSL 1.1 | MPL 2.0 (Linux Foundation) |
| HCL compatibility | — | High; diverging slowly |
terraform test |
Since 1.6 | Equivalent |
| Client-side state encryption | Not native | Yes, a feature of its own |
| Module registry | Terraform Registry | Its own registry + compatible |
| Terragrunt | Compatible | Compatible |
What is relevant for this lesson:
- Terragrunt works with both. You select it with
terraform_binary = "tofu"in the configuration or with theTERRAGRUNT_TFPATHenvironment variable. - Gruntwork, the company behind Terragrunt, has explicitly backed OpenTofu, and much of the recent documentation assumes it.
- For EcoMarket this is an architecture and risk decision that changes nothing you have learned in the course. The BSL does not affect internal use by a company that does not sell a product competing with Terraform; it is worth having the legal team confirm it if the company offers managed services to third parties.
The whole rest of the lesson works identically with either one.
- Installation and the first
terragrunt.hcl
terragrunt.hcl# Linux
curl -Lo /tmp/terragrunt \
https://github.com/gruntwork-io/terragrunt/releases/download/v0.67.16/terragrunt_linux_amd64
sudo install -m 0755 /tmp/terragrunt /usr/local/bin/terragrunt
# macOS
brew install terragrunt
# Verify. It also shows which Terraform binary it will use.
terragrunt --version
# terragrunt version v0.67.16Pin the Terragrunt version the way you pin Terraform's. Just like .terraform-version, a .terragrunt-version file in the repository is worthwhile: a different version can generate different configuration and produce a different plan from the same code.
The simplest possible file:
# live/eu-west-1/dev/network/terragrunt.hcl
terraform {
# Which module to apply. It is the only mandatory thing.
source = "git::[email protected]:ecomarket/terraform-aws-ecomarket-network.git//?ref=v3.4.1"
}
# The module's inputs. Terragrunt passes them as TF_VAR_*.
inputs = {
base_name = "ecomarket-dev"
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
subnet_bits = 8
create_nat = false
}cd live/eu-west-1/dev/network
terragrunt plan # equivalent to: download the module + terraform init + plan
terragrunt applyThere is still no generated backend and no inheritance: that comes in the following sections. But the shape is already visible: a root is a file that says which module and with what inputs.
terraform { source }: the versioned module
terraform { source }: the versioned moduleThe terraform block is the bridge between Terragrunt and the real module. Its source argument accepts the same forms as a module source, with one extension of its own.
| Form | Example | Use |
|---|---|---|
| Git with a tag | git::[email protected]:org/module.git//?ref=v3.4.1 |
Production: an immutable version |
| Git with a subdirectory | git::...//modules/network?ref=v3.4.1 |
A module monorepo |
| Terraform registry | tfr:///ecomarket/ecomarket-network/aws?version=3.4.1 |
Published modules |
| Local path | ../../../modules/network |
Local development |
Local path with // |
${get_repo_root()}/modules/network |
Monorepo, with no download |
The // syntax separates the repository root from the subdirectory inside it, exactly as in the Terraform source values from 04-03. And ?ref= pins the version, which is non-negotiable in production for the reasons in 07-04 §15: there is no lock file for modules.
Local development without changing the file
A practical problem: while you develop a module you want to test your local changes, but you do not want to modify the terragrunt.hcl and risk merging it with a local path.
# --terragrunt-source overrides the `source` WITHOUT touching the file.
# The suffix after // in the original source is preserved.
terragrunt plan --terragrunt-source ~/projects/ecomarket-modules
# Or with the environment variable, for a whole session:
export TERRAGRUNT_SOURCE=~/projects/ecomarket-modules
terragrunt run-all planThis is one of the things Terragrunt does better than plain Terraform, where testing a module change means editing the source and remembering to revert it.
remote_state with generate: the backend.tf solved
remote_state with generate: the backend.tf solvedHere is the solution to symptom 1, and it is the main reason most teams adopt Terragrunt.
Recall the underlying limitation, from 03-03: the backend block accepts neither variables nor interpolation, because it is resolved before anything is evaluated. That limitation is what forces you to have 36 nearly identical files, or to pass -backend-config by hand as EcoMarket does in 07-01 §6.1.
Terragrunt solves it by a different route: it generates the file.
# live/terragrunt.hcl — the ROOT file. One single one for the 36 roots.
remote_state {
backend = "s3"
generate = {
# Write this file into the temporary directory before the init.
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
config = {
bucket = "ecomarket-tfstate-${local.account}"
# THE KEY POINT: the state path is DERIVED from the directory path.
# live/eu-west-1/prod/data → eu-west-1/prod/data/terraform.tfstate
# It is impossible for two components to share a key by mistake.
key = "${path_relative_to_include()}/terraform.tfstate"
region = local.region
encrypt = true
kms_key_id = local.kms_key_arn
use_lockfile = true
# Terragrunt can create the bucket if it does not exist, with versioning
# and encryption. Useful for new regions; disabled at EcoMarket
# because bootstrapping is a reviewed process (07-04 §9).
disable_bucket_update = true
}
}path_relative_to_include() is the function that does the work. It returns the current directory's path relative to the file being included, and the state key comes out of it.
| Directory | path_relative_to_include() |
Generated state key |
|---|---|---|
live/eu-west-1/dev/network |
eu-west-1/dev/network |
eu-west-1/dev/network/terraform.tfstate |
live/eu-west-1/prod/data |
eu-west-1/prod/data |
eu-west-1/prod/data/terraform.tfstate |
live/eu-central-1/staging/app |
eu-central-1/staging/app |
eu-central-1/staging/app/terraform.tfstate |
This is what eliminates symptom 1's error at the root. Nobody writes the key: it is derived from where the file is. Two regions cannot share state through a careless copy, because there is nowhere to copy the key wrongly.
And when security asks for kms_key_id to be added, it is one line in one file, not 36.
# Look at the generated file, which is the first thing you want to check.
terragrunt plan
cat .terragrunt-cache/*/*/backend.tf# GENERATED backend.tf — it is not in Git, nobody edits it.
terraform {
backend "s3" {
bucket = "ecomarket-tfstate-123456789014"
key = "eu-west-1/prod/data/terraform.tfstate"
region = "eu-west-1"
encrypt = true
kms_key_id = "arn:aws:kms:eu-west-1:123456789014:key/abc-123"
use_lockfile = true
}
}if_exists value |
Behaviour |
|---|---|
overwrite_terragrunt |
Overwrites only if Terragrunt generated it. The recommended one |
overwrite |
Always overwrites, including a hand-written file |
skip |
Does not generate if it already exists |
error |
Fails if it exists. Useful during a migration, to detect leftovers |
generate "provider": the provider that stops being copied
generate "provider": the provider that stops being copiedThe same mechanism, applied to symptom 2.
# live/terragrunt.hcl (continuing the root file)
generate "provider" {
path = "provider.tf"
if_exists = "overwrite_terragrunt"
contents = <<-EOF
provider "aws" {
region = "${local.region}"
assume_role {
role_arn = "arn:aws:iam::${local.account}:role/ecomarket-terraform-${local.environment}"
session_name = "tg-${local.environment}-${get_env("CI_RUN_ID", "local")}"
}
default_tags {
tags = {
Project = "ecomarket"
Environment = "${local.environment}"
Region = "${local.region}"
ManagedBy = "terraform"
Owner = "[email protected]"
Repo = "ecomarket-infra"
TgPath = "${path_relative_to_include()}"
}
}
}
EOF
}
generate "versions" {
path = "versions_terragrunt.tf"
if_exists = "overwrite_terragrunt"
contents = <<-EOF
terraform {
required_version = "~> 1.9"
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.60" }
random = { source = "hashicorp/random", version = "~> 3.6" }
http = { source = "hashicorp/http", version = "~> 3.4" }
}
}
EOF
}The TgPath tag deserves a comment: it puts the path of the component that created it on every resource. When somebody finds an orphan resource in the console, that tag tells them exactly which terragrunt.hcl manages it. It is the at-scale version of the Repo tag from 07-01 §5, and in a repository with 36 roots it is worth its weight in gold.
Important warning about
generate "versions". Generating therequired_providersblock has a side effect worth understanding: the.terraform.lock.hclis generated inside the temporary directory and is not versioned, so the supply-chain defence from 07-04 §15 is lost. There are two solutions, and the first is the one to prefer:
- Leave
required_providersinside the module (which is versioned, with its lock in its own repository) and do not generate it here. The module declares which providers it needs; that is its responsibility.- Use
copy_terraform_lock_file = true(available in recent versions) so that Terragrunt copies the lock from theterragrunt.hcldirectory into the temporary one, which allows versioning it per component.If you adopt Terragrunt and this decision has not been taken consciously, you have taken it without noticing and the default answer is the worst one.
include and find_in_parent_folders(): inheritance by levels
include and find_in_parent_folders(): inheritance by levelsinclude is what connects each root to the common configuration. And find_in_parent_folders() searches upwards in the directory tree until it finds a terragrunt.hcl (or whatever name you give it).
# live/eu-west-1/prod/data/terragrunt.hcl — a complete root, 20 lines.
# 1. Inherit from the root terragrunt.hcl: backend, provider, versions.
include "root" {
path = find_in_parent_folders()
}
# 2. Inherit from THIS component's common configuration, shared
# by the 12 region-and-environment combinations.
include "envcommon" {
path = "${dirname(find_in_parent_folders())}/_envcommon/data.hcl"
# expose lets you read the included file's locals from here.
expose = true
# merge_strategy: how the `inputs` of both files are combined.
merge_strategy = "deep"
}
# 3. And here, ONLY what is specific to this combination.
inputs = {
db_class = "db.t3.medium"
high_availability = true
retention_days = 30
protect_deletion = true
}Inheritance by levels
flowchart TD
R["live/terragrunt.hcl<br/><b>ROOT</b><br/>remote_state · generate provider<br/>locals: account, region, environment"]
E["_envcommon/data.hcl<br/><b>COMPONENT</b><br/>module source<br/>common inputs · dependency"]
H["live/eu-west-1/prod/data/terragrunt.hcl<br/><b>LEAF</b><br/>only its own: sizing"]
R -->|"include root"| H
E -->|"include envcommon"| H
H --> RES["Final configuration:<br/>generated backend + generated provider<br/>+ source + combined inputs"]
style R fill:#f3e8fd,stroke:#7c3aed
style E fill:#e0f2fe,stroke:#0369a1
style H fill:#dcfce7,stroke:#15803d
| Level | What it contains | How many files | Changes |
|---|---|---|---|
| Root | Backend, provider, versions, locals derived from the path |
1 | Almost never |
_envcommon/<component>.hcl |
The module's source, common inputs, dependencies |
1 per component (3) | When the module version is bumped |
| Leaf | Only what distinguishes this combination | 36 | When sizing changes |
36 roots, 4 common configuration files. That is the inversion of the ratio from section 1.
Combining inputs
The merge_strategy decides what happens when the parent and the child define the same input:
| Strategy | Behaviour |
|---|---|
no_merge |
The child replaces the parent's inputs entirely |
shallow (default) |
Top-level keys are combined; the child wins |
deep |
Nested maps are combined too, recursively |
deep is what you want almost always, because it lets the parent define a map of tags or of configuration and the child add a key without rewriting the whole thing. The trap is in lists: deep replaces them, it does not concatenate. If the parent defines zones = ["a","b","c"] and the child zones = ["a"], the result is ["a"].
locals and read_terragrunt_config
locals and read_terragrunt_configThe root terragrunt.hcl needs to know which region, environment and account it is in. And that information is in the directory path. There are two ways of getting it, and one is far better than the other.
The fragile way: parsing the path
# live/terragrunt.hcl — IT WORKS, but it is fragile.
locals {
parts = split("/", path_relative_to_include())
region = local.parts[0] # eu-west-1
environment = local.parts[1] # prod
}The problem is obvious as soon as somebody adds a level to the tree, or creates a directory that does not follow the pattern: the indices shift and the resulting error is opaque. It works and it is not recommended.
The robust way: configuration files per level
# live/eu-west-1/region.hcl
locals {
region = "eu-west-1"
zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
cidr_base = "10.20.0.0/16"
domain = "ecomarket.example.com"
kms_key_arn = "arn:aws:kms:eu-west-1:ACCOUNT:key/abc-123"
}# live/eu-west-1/prod/environment.hcl
locals {
environment = "prod"
account = "123456789014"
profile = "high-availability"
protect_deletion = true
# The account guard from 06-05, now declared here.
expected_account = "123456789014"
}# live/terragrunt.hcl — the root, reading those files.
locals {
# read_terragrunt_config reads another HCL file and returns its contents.
# find_in_parent_folders searches upwards: it works from any
# depth in the tree without relying on indices.
cfg_region = read_terragrunt_config(find_in_parent_folders("region.hcl"))
cfg_environment = read_terragrunt_config(find_in_parent_folders("environment.hcl"))
region = local.cfg_region.locals.region
zones = local.cfg_region.locals.zones
environment = local.cfg_environment.locals.environment
account = local.cfg_environment.locals.account
kms_key_arn = replace(local.cfg_region.locals.kms_key_arn, "ACCOUNT", local.account)
}The advantages over parsing the path:
- The data lives where it is read. To know which CIDR Frankfurt uses you open
live/eu-central-1/region.hcl, you do not deduce it from a function. - Structural changes break nothing. Adding a directory level does not shift any index.
- It is reviewable. A PR that changes the production account is a one-line diff in a clearly named file, and it can be given
CODEOWNERS(07-02 §11). - It is the natural extension point. A new region is a directory with its
region.hcl.
The catalogue of useful functions
| Function | Returns | Typical use |
|---|---|---|
find_in_parent_folders() |
The path to the nearest parent terragrunt.hcl |
The include "root" |
find_in_parent_folders("name.hcl") |
The path to that specific file, searching upwards | Reading region.hcl, environment.hcl |
path_relative_to_include() |
The path relative to the included file | The state key |
path_relative_from_include() |
The inverse (../../..) |
Building paths to local modules |
get_repo_root() |
The Git repository root | source for monorepo modules |
get_terragrunt_dir() |
The current terragrunt.hcl's directory |
Paths to auxiliary files |
get_parent_terragrunt_dir() |
The included terragrunt.hcl's directory |
Common paths |
get_env("VAR", "default") |
An environment variable | The CI run identifier |
get_aws_account_id() |
The account of the active credentials | Account guards |
read_terragrunt_config(path) |
The contents of another HCL file | Configuration by levels |
run_cmd("--terragrunt-quiet", ...) |
A command's output | A last resort; it runs on every parse |
The account guard, the Terragrunt way
The guard from 06-05 is still valid inside the module, and now a check can be added before invoking Terraform, which fails in a second instead of after a plan:
# live/terragrunt.hcl
locals {
expected_account = local.cfg_environment.locals.account
active_account = get_aws_account_id()
# Terragrunt has no `assert` block, so the trick is an expression
# that fails when evaluated if the condition does not hold.
# Ugly, and the message comes out in the error.
_account_guard = local.active_account == local.expected_account ? true : file("ERROR: the active account ${local.active_account} is not the one expected for ${local.environment} (${local.expected_account}). Check AWS_PROFILE.")
}It is a workaround, and it has to be said: Terragrunt has no assertion mechanism of its own. The file() call on a non-existent string produces an error that includes the message. It works, but it is exactly the kind of thing that gives Terragrunt a reputation for being magical. The «real» guard, the one that blocks the apply with a clear message, is still the precondition from 06-05 inside the module.
dependency and mock_outputs: the chaining solved
dependency and mock_outputs: the chaining solvedThis is the feature that solves symptoms 3 and 4 at once, and the second main reason to adopt Terragrunt.
# _envcommon/app.hcl — the `app` component's common configuration.
terraform {
source = "git::[email protected]:ecomarket/terraform-aws-ecomarket-app.git//?ref=v3.6.2"
}
# --- Dependency on the network layer ---
dependency "network" {
config_path = "../network"
# mock_outputs: values used WHEN the dependency has not been
# applied yet. Without this, `run-all plan` over brand-new
# infrastructure fails, because `app` cannot plan without the vpc_id.
mock_outputs = {
vpc_id = "vpc-0000000000000000"
private_subnets = {
"zone-a" = { id = "subnet-00000000000000001", cidr = "10.0.1.0/24", zone = "zone-a" }
"zone-b" = { id = "subnet-00000000000000002", cidr = "10.0.2.0/24", zone = "zone-b" }
}
web_sg_id = "sg-00000000000000000"
}
# CRITICAL: the mocks are ONLY used in these commands. In a real
# `apply`, if the dependency is not applied, Terragrunt FAILS
# instead of creating resources pointing at a non-existent VPC.
mock_outputs_allowed_terraform_commands = ["plan", "validate", "destroy", "refresh"]
# They are also ignored if the dependency IS already applied: as soon
# as a state with real outputs exists, the real ones are used.
skip_outputs = false
}
# --- Dependency on the data layer ---
dependency "data" {
config_path = "../data"
mock_outputs = {
db_endpoint = "mock-db.eu-west-1.rds.amazonaws.com:5432"
secret_arn = "arn:aws:secretsmanager:eu-west-1:000000000000:secret:mock"
images_bucket = "mock-bucket"
}
mock_outputs_allowed_terraform_commands = ["plan", "validate", "destroy", "refresh"]
}
inputs = {
# The outputs are consumed like any other value. Not a single
# `terraform_remote_state` block, not a single repeated backend
# configuration: symptom 3 disappears.
vpc_id = dependency.network.outputs.vpc_id
subnets = dependency.network.outputs.private_subnets
web_sg_id = dependency.network.outputs.web_sg_id
db_endpoint = dependency.data.outputs.db_endpoint
db_secret_arn = dependency.data.outputs.secret_arn
images_bucket = dependency.data.outputs.images_bucket
}Why mock_outputs is both essential and dangerous
The problem it solves: without mocks, planning a whole new region is impossible. app needs the vpc_id that network will produce, but network has not been applied yet, so its state has no outputs. run-all plan fails at the first dependent component.
The danger: a fake value that reaches a real apply creates resources pointing at non-existent infrastructure, or worse, at somebody else's. Hence mock_outputs_allowed_terraform_commands, which is the block's most important argument and the one most people forget.
| Situation | What Terragrunt does |
|---|---|
plan, the dependency is not applied |
It uses the mocks. The plan is indicative, not exact |
plan, the dependency is applied |
It uses the real outputs. The mocks are ignored |
apply, the dependency is not applied |
It FAILS, if apply is not in the list of allowed commands |
destroy, the dependency already destroyed |
It uses the mocks, so that it can destroy in reverse order |
Never put apply in mock_outputs_allowed_terraform_commands. It is the only genuinely dangerous rule in this section: it would allow creating a security group in the VPC vpc-0000000000000000, which either does not exist (a confusing error) or does exist and belongs to somebody else (an incident).
dependencies with no outputs
When only the order is needed, with no outputs consumed:
# It only orders. It reads nothing from the other component.
dependencies {
paths = ["../network", "../../shared/dns"]
}Useful for implicit dependencies: a component that needs a DNS zone to exist, even though it references it by name and not by identifier.
run-all and the dependency graph
run-all and the dependency graphWith the dependency blocks declared, Terragrunt builds the graph and walks it in order, parallelising what it can.
# Plan EVERYTHING under this directory, in order.
cd live/eu-west-1/prod
terragrunt run-all plan
# Apply everything. With per-component confirmation unless -auto-approve.
terragrunt run-all apply
# Destroy: it walks the graph in REVERSE order automatically.
terragrunt run-all destroy
# See the graph, to understand what will run and in what order.
terragrunt graph-dependencies | dot -Tpng > graph.pngA note on versions. In recent Terragrunt,
run-allis being migrated toterragrunt run --all <command>, and the concepts of unit and stack (terragrunt.stack.hcl) have appeared for composing sets of components. Therun-allform still works and it is the one you will see in most existing repositories. Check the documentation of the version you pin in.terragrunt-version.
flowchart TD
subgraph ORDER["The execution order Terragrunt deduces"]
direction TB
N1["Level 1 (in PARALLEL)"]
R1["eu-west-1/prod/network"]
R2["eu-west-3/prod/network"]
N2["Level 2 (in PARALLEL)"]
D1["eu-west-1/prod/data"]
D2["eu-west-3/prod/data"]
N3["Level 3"]
A1["eu-west-1/prod/app"]
A2["eu-west-3/prod/app"]
end
N1 --- R1
N1 --- R2
R1 --> D1
R2 --> D2
N2 --- D1
N2 --- D2
D1 --> A1
D2 --> A2
R1 --> A1
R2 --> A2
N3 --- A1
N3 --- A2
style R1 fill:#dcfce7,stroke:#15803d
style D1 fill:#fef9c3,stroke:#a16207
style A1 fill:#e0f2fe,stroke:#0369a1
What to take from the diagram: the two regions are deployed in parallel, because they do not depend on each other, while inside each one the network → data → app order is respected. That turns symptom 4's 24-step manual procedure into a single command, and does it in half the time.
The arguments you actually need
# Limit the parallelism: 36 runs at once exhaust AWS's
# API limits and produce rate-limiting errors.
terragrunt run-all apply --terragrunt-parallelism 4
# Exclude directories (one with a known problem, for instance).
terragrunt run-all plan --terragrunt-exclude-dir "**/observability"
# Include ONLY certain directories.
terragrunt run-all plan --terragrunt-include-dir "*/prod/*"
# Carry on after an error, instead of stopping at the first one.
# Useful for seeing the full picture; dangerous in an apply.
terragrunt run-all plan --terragrunt-ignore-dependency-errors
# Do not ask. ONLY in the pipeline, never in a human terminal.
terragrunt run-all apply --terragrunt-non-interactive -auto-approveWarning.
run-all applyover a production directory can touch dozens of components in a single run. It is the opposite of the contained blast radius that justified separating states in 07-01 §6.3. EcoMarket's recommendation:run-all planyes,run-all applyonly to create a new environment from scratch. Day to day it isterragrunt applyon one component, with its plan reviewed.run-allis a construction tool, not an operations tool.
- EcoMarket's structure with Terragrunt
The complete tree, commented:
ecomarket-infra/
├── .terragrunt-version # v0.67.16 — pins the version
├── .gitignore # includes .terragrunt-cache/
├── CODEOWNERS
├── README.md
│
├── modules/ # the modules, UNTOUCHED
│ ├── network/ data/ app/ # (the stable ones are published)
│ └── observability/ # this one is still being run in
│
├── live/ # ← what gets deployed
│ │
│ ├── terragrunt.hcl # ROOT: backend + provider
│ │ # generated. ONE file for 36.
│ │
│ ├── _envcommon/ # configuration per COMPONENT
│ │ ├── network.hcl # source + common inputs
│ │ ├── data.hcl # + dependency on network
│ │ ├── app.hcl # + dependency on network and data
│ │ └── observability.hcl
│ │
│ ├── eu-west-1/
│ │ ├── region.hcl # region, zones, CIDR, KMS, domain
│ │ │
│ │ ├── dev/
│ │ │ ├── environment.hcl # environment, account ...012, profile
│ │ │ ├── network/terragrunt.hcl # ← 6 lines
│ │ │ ├── data/terragrunt.hcl # ← 8 lines
│ │ │ └── app/terragrunt.hcl # ← 8 lines
│ │ │
│ │ ├── staging/
│ │ │ ├── environment.hcl # account ...013
│ │ │ └── network/ data/ app/
│ │ │
│ │ └── prod/
│ │ ├── environment.hcl # account ...014
│ │ └── network/ data/ app/ observability/
│ │
│ ├── eu-west-3/ # Paris: SAME shape
│ │ ├── region.hcl # 10.30.0.0/16
│ │ └── dev/ staging/ prod/
│ │
│ ├── eu-south-1/ # Milan
│ │ ├── region.hcl # 10.40.0.0/16
│ │ └── dev/ staging/ prod/
│ │
│ ├── eu-central-1/ # Frankfurt
│ │ ├── region.hcl # 10.50.0.0/16
│ │ └── dev/ staging/ prod/
│ │
│ └── _global/ # what has NO region
│ ├── dns/terragrunt.hcl # Route 53 zone
│ └── iam/terragrunt.hcl # shared roles
│
├── ci/
│ ├── policies/ # the 07-04 ones, unchanged
│ ├── plan.sh # now wraps terragrunt
│ └── apply.sh
│
└── docs/adr/
└── 0012-adopt-terragrunt.md # why, when and what was evaluatedAnd this is what a leaf of the tree looks like:
# live/eu-central-1/prod/data/terragrunt.hcl — the COMPLETE root.
include "root" {
path = find_in_parent_folders()
}
include "envcommon" {
path = "${dirname(find_in_parent_folders())}/_envcommon/data.hcl"
merge_strategy = "deep"
}
inputs = {
db_class = "db.t3.medium"
high_availability = true
retention_days = 30
}Thirteen lines. No backend.tf, no providers.tf, no versions.tf, no terraform_remote_state, no variables.tf redeclaring what the module already declares. Compare it with the four or five files the same root would have under strategy 2 of 07-01.
| Count | Without Terragrunt (strategy 2) | With Terragrunt |
|---|---|---|
backend.tf |
36 | 0 (generated from 1 block) |
providers.tf |
36 | 0 (generated from 1 block) |
versions.tf |
36 | 0 or 1 (see the warning in section 7) |
data "terraform_remote_state" |
~24 blocks | 0 (dependency) |
| Files defining the sizing | 36 | 36 (of 13 lines) |
| Common configuration files | 0 | 4 + 4 region.hcl + 12 environment.hcl |
| Total files to maintain | ~150 | ~56 |
The reduction is real and at the same time the second-to-last row is worth reading: 20 new files appear (region.hcl, environment.hcl, _envcommon/). It is not that the configuration disappears, it is that it stops being duplicated. That is exactly what you are buying.
- Hooks and
extra_arguments
extra_argumentsTwo mechanisms that in practice solve annoying details.
extra_arguments: adding arguments to every command
# live/terragrunt.hcl
terraform {
# Automatically load the common .tfvars and the environment's,
# WITHOUT having to write -var-file on every command.
extra_arguments "variable_files" {
commands = ["plan", "apply", "destroy", "refresh", "import"]
optional_var_files = [
"${get_parent_terragrunt_dir()}/common.tfvars",
"${get_terragrunt_dir()}/override.tfvars",
]
}
# Retries and parallelism, on all the commands where they apply.
extra_arguments "common" {
commands = ["plan", "apply", "destroy"]
arguments = ["-lock-timeout=20m"]
}
# -lockfile=readonly on the init: the supply-chain
# defence from 07-04 §15, applied consistently.
extra_arguments "locked_init" {
commands = ["init"]
arguments = ["-lockfile=readonly"]
}
}optional_var_files does not fail if the file does not exist, unlike required_var_files. That is what allows one specific component to have an override.tfvars while the others do not.
Hooks: running something before or after
terraform {
# BEFORE every plan and apply: verify the active account.
# It fails in a second if the credentials are not the right ones.
before_hook "check_account" {
commands = ["plan", "apply"]
execute = [
"bash", "-c",
<<-EOT
CURRENT=$(aws sts get-caller-identity --query Account --output text)
EXPECTED="${local.account}"
if [ "$CURRENT" != "$EXPECTED" ]; then
echo "ERROR: active account $CURRENT, expected $EXPECTED for ${local.environment}."
echo "Run: export AWS_PROFILE=ecomarket-${local.environment}"
exit 1
fi
EOT
]
}
# AFTER every plan: apply the 07-04 policies.
# This is what makes the control run ALWAYS, without
# depending on the pipeline remembering to invoke it.
after_hook "policies" {
commands = ["plan"]
execute = ["${get_repo_root()}/ci/policies.sh"]
run_on_error = false
}
# When an apply finishes WITH AN ERROR: alert the channel.
error_hook "notify_failure" {
commands = ["apply"]
on_errors = [".*"]
execute = ["${get_repo_root()}/ci/notify.sh", "${local.environment}", "${path_relative_to_include()}"]
}
}The policies after_hook deserves underlining: putting the Conftest run there makes the control run when somebody plans from their laptop too, not only in the pipeline. It is the same idea as the ci/plan.sh from 07-01 §8 — that the human and the machine run the same thing — now guaranteed by the tool.
Although, being rigorous with the distinction from 07-04: a hook is not a control, because it lives in the same repository and can be deleted. The control is still the pipeline's required check. The hook is ergonomics: it makes the failure show up sooner.
- What it solves and what it does NOT solve
The honest table, which is the most useful thing in this lesson.
| Problem | Does it solve it? | How, or why not |
|---|---|---|
Duplicated, out-of-sync backend.tf |
Yes, completely | remote_state + generate + path_relative_to_include() |
Duplicated provider and required_providers |
Yes | generate "provider", with the lock caveat (section 7) |
Repeated terraform_remote_state |
Yes | dependency, with mocks for planning before applying |
apply order between components |
Yes | The run-all graph, with parallelism |
| Repeated common inputs | Yes | include with inheritance by levels |
| Per-environment sizing configuration | Partly | There are still 36 files, but of 13 lines |
| Selecting a provider instance dynamically | Yes | It is the second limitation 06-01 pointed out. With generate, the provider block is written with the region and account values already resolved: each root has its provider, generated, with no aliases and no conditionals |
Blast radius of the plan |
No | That is determined by how the state was split, not by the tool |
Duration of a component's apply |
No | It is the same Terraform. run-all parallelises between components |
| Infrastructure drift | No | You still need the nightly plan from 07-01 §11 |
| Security and permissions | No | All of 07-04 applies unchanged. Terragrunt does not change which role is assumed |
| Policies and static analysis | No | They are integrated with hooks, but the control is still in the pipeline |
| Code testing | No | terraform test runs over the modules, just as in 07-03 |
| Module quality | No | A bad module wrapped in Terragrunt is still a bad module |
| Versioning and promotion | No, but it fits | The source's ?ref= is the promotion mechanism from 07-02 §6 |
| State locking | No | The backend does that. Terragrunt only configures it |
The dynamic-provider row deserves an explanation, because it is one of the two limitations the course explicitly flagged and that Terragrunt does solve. In plain Terraform, provider accepts neither for_each nor count, and provider = aws.region_x cannot be an expression. That forces you to declare one alias per region and to repeat blocks. With Terragrunt, each root generates its own provider block with the region and the role already substituted: there is no aliased provider to choose, there is one provider per directory.
And the conclusion that organises the table: Terragrunt solves duplication and orchestration problems. It solves no architecture, security or quality problem. If the repository has a 2,000-resource state and catch-all modules, Terragrunt leaves it exactly as it was, only with fewer repeated files.
- The cost of adopting it
Four concrete, measurable and permanent costs.
One more dependency
Terragrunt is third-party software, with its own release cycle and its own breaking changes. A real example: the migration from run-all to run --all and the introduction of stacks have changed commands and concepts between minor versions. That means pinning the version, reading the changelogs and planning upgrades, exactly as with any other dependency.
One layer of indirection
What runs is no longer what you read. Answering «which backend is this using?» means following the include, reading the remote_state, understanding path_relative_to_include() and, in practice, running a command:
# The fundamental debugging tool: see the RESOLVED
# configuration, with all the includes combined.
terragrunt terragrunt-info
terragrunt render-json --terragrunt-json-out resolved.json
jq '.remote_state.config.key' resolved.jsonAnybody new to the repository will have to learn that. It is a real training cost, small but recurring.
Harder error messages
It is the cost that hurts most during an incident. An error can come from three different places and the message does not always make it clear:
| Origin | Typical symptom |
|---|---|
| Terragrunt itself | «Error resolving dependency», «Could not find config file» |
| The generated file | A Terraform error pointing at .terragrunt-cache/xxxx/yyyy/backend.tf, a file you did not write |
| Terraform itself | The normal error, but with temporary-directory paths |
# The three tools you need when something does not add up.
# 1. Detailed logging.
terragrunt plan --terragrunt-log-level debug
# 2. Look at the generated files, which are what actually runs.
find .terragrunt-cache -name "*.tf" -newer terragrunt.hcl -exec cat {} +
# 3. Run terraform DIRECTLY in the temporary directory,
# to rule out the problem being Terragrunt's.
cd .terragrunt-cache/*/*/ && terraform planPoint 3 is the technique that fastest separates «this is a Terragrunt problem» from «this is a problem with my Terraform». In-depth debugging, including reading TF_LOG, belongs to 09-02.
Fewer people know it
It is a hiring and onboarding cost. Most profiles with Terraform experience have not used Terragrunt, and the documentation, the examples and the community answers are far fewer. In a small team with turnover, this cost can outweigh everything it saves.
Warning. Adopting Terragrunt is an architectural decision that affects the whole team and is expensive to reverse. Write it down in an ADR (
docs/adr/), with the measured symptoms that justify it — «12 combinations, 36backend.tffiles, two incidents from drift in six months» — the alternatives evaluated and who approved it. If in two years' time somebody asks why, the answer should be a document with data, not a preference.
- Alternatives compared
Terragrunt is not the only way out. These are the five real options, with decision criteria.
| Option | What it is | Solves the duplication | Cost | Ties you to |
|---|---|---|---|---|
| Do nothing | Directories and .tfvars (07-01) |
No, but perhaps you do not need to | None | Nothing |
| Terragrunt | A wrapper that generates and orchestrates | Yes, a lot | A dependency + indirection | Gruntwork (open) |
| HCP Terraform | A managed service: workspaces, variables, state, policies | Yes, by another route | Money + network | HashiCorp |
| Your own generation | Scripts or templates that write the .tf files |
Yes | Maintaining your own tool | Yourself |
| CDKTF | Defining infrastructure in TypeScript, Python, Go | Yes, with the language's loops | A steep curve, less maturity | HashiCorp + the language |
| Native stacks | A HashiCorp feature for composing deployments | Promising | Depends on the platform | HashiCorp |
Terragrunt versus HCP Terraform
It is the most frequent comparison and the one that generates the most confusion, because they solve the same thing by opposite routes.
| Criterion | Terragrunt | HCP Terraform |
|---|---|---|
| Where it runs | Your pipeline, your infrastructure | A managed service (or your own agents) |
| State | Your S3 backend | The service's |
| Backend duplication | Generated | It does not exist: the workspace is the state |
| Provider duplication | Generated | Workspace variables |
| Dependencies between components | dependency |
Triggers between workspaces |
| Orchestration | run-all with a graph |
Triggers, with no complete graph |
| Policies | Conftest in the pipeline | Integrated Sentinel (08-04) |
| Cost estimation | An external tool | Built in |
| Financial cost | Free | Per managed resource |
| Approvals and auditing | The repository's and the CI's | Built into the product |
| Works offline | Yes | No |
The decision criterion: if you already have a mature pipeline, OIDC credentials, Conftest policies and an S3 backend that works, Terragrunt fits on top without changing anything. If you are starting out and would rather not operate that machinery, HCP Terraform replaces all of it, in exchange for money and for being tied to the platform. The detail is in 08-04.
Your own generation with templates
The temptation is strong: a fifty-line script that generates the 36 backend.tf files from a template.
# scripts/generate-backends.sh — the "home-made" alternative.
for REGION in eu-west-1 eu-west-3 eu-south-1 eu-central-1; do
for ENVIRONMENT in dev staging prod; do
for COMP in network data app; do
mkdir -p "live/${REGION}/${ENVIRONMENT}/${COMP}"
sed -e "s/{{REGION}}/${REGION}/g" \
-e "s/{{ENVIRONMENT}}/${ENVIRONMENT}/g" \
-e "s/{{COMPONENT}}/${COMP}/g" \
templates/backend.tf.tpl > "live/${REGION}/${ENVIRONMENT}/${COMP}/backend.tf"
done
done
done| In favour | Against |
|---|---|
| Zero external dependencies | You maintain your own tool, with no community and no documentation |
| Exactly what you need | It grows: first the backend, then the provider, then the dependencies... |
Everybody understands sed |
It solves the generation, not the orchestration or the chaining |
| The generated files are visible in Git | Either they are versioned (and the diff is noise) or they are not (and they cannot be reviewed) |
Honesty requires saying it: a home-made generator that grows ends up being a worse Terragrunt, with no tests, no documentation and maintained by one person. If the problem is only the backend and nothing else, a script is fine. Once the order of application appears, it is not.
CDKTF
Defining the infrastructure in a programming language that synthesises Terraform JSON:
// The 36 roots as a loop. That is its big selling point.
const regions = ["eu-west-1", "eu-west-3", "eu-south-1", "eu-central-1"];
const environments = ["dev", "staging", "prod"];
for (const region of regions) {
for (const environment of environments) {
new PlatformStack(app, `ecomarket-${region}-${environment}`, {
region,
environment,
profile: environment === "prod" ? "high-availability" : "minimal",
});
}
}It is elegant and it has serious costs: the community is much smaller, the generated JSON is hard to review in a PR (the diff is unreadable), the ecosystem's tools — tflint, Checkov, Conftest — work less well on it, and you have to know the language. For an infrastructure team that already knows HCL, it rarely pays off. For a development team that wants to manage its own infrastructure in the language it already uses, it can make sense.
The honest recommendation
flowchart TD
A{"How many combinations of<br/>environment × region × component?"} -->|"Fewer than 10"| NO["<b>Adopt nothing.</b><br/>The directories and .tfvars<br/>from 07-01 are enough"]
A -->|"10 or more"| B{"Has the duplication caused<br/>a REAL incident?"}
B -->|"Not yet"| WAIT["Wait. Measure.<br/>Document the symptoms"]
B -->|"Yes, measured"| C{"Do you have a mature pipeline,<br/>OIDC and your own policies?"}
C -->|"No"| HCP["Evaluate HCP Terraform:<br/>it replaces the machinery<br/>(08-04)"]
C -->|"Yes"| D{"Are there ORDER<br/>dependencies between components?"}
D -->|"No, just the backend"| SCRIPT["A generation script<br/>may be enough"]
D -->|"Yes"| TG["<b>Terragrunt</b><br/>with an ADR justifying it"]
style NO fill:#dcfce7,stroke:#15803d
style TG fill:#e0f2fe,stroke:#0369a1
style WAIT fill:#fef9c3,stroke:#a16207
The green box is the right answer for most teams, and that is why it comes first.
- Progressive migration without touching the state
The good news: migrating to Terragrunt does not touch the state. The resources stay where they are, the addresses do not change, the backend is the same bucket. The only thing that changes is who writes the backend.tf and how the inputs are passed.
The non-negotiable condition, the same as in every migration in the course: a zero plan at every step.
The procedure, step by step
# ---------- STEP 0: the safety net ----------
# A backup of the state of every component to be migrated.
for COMP in network data app; do
terraform -chdir="infra/${COMP}" state pull > "backup-${COMP}-$(date +%F).tfstate"
done
# And the reference plan: how things are TODAY, before touching anything.
# If the starting plan is not at zero, fix it BEFORE migrating.
terraform -chdir=infra/network plan -detailed-exitcode
# exit code 0 = no changes. If it gives 2, there is drift: resolve it first.# ---------- STEP 1: note the EXACT state key ----------
# It is the critical piece of the whole migration. If the generated key
# does not match the current one, Terragrunt will point at an empty state
# and the plan will propose creating ALL the infrastructure from scratch.
terraform -chdir=infra/network init -backend-config=backends/dev.hcl
cat infra/network/.terraform/terraform.tfstate | jq '.backend.config | {bucket, key, region}'
# {
# "bucket": "ecomarket-tfstate-123456789012",
# "key": "ecomarket/dev/network/terraform.tfstate", ← THIS string
# "region": "eu-west-1"
# }# ---------- STEP 2: the root terragrunt.hcl, with the CURRENT key ----------
# path_relative_to_include() is NOT used yet: first you have to
# reproduce exactly what is there. The tidy path comes later.
remote_state {
backend = "s3"
generate = { path = "backend.tf", if_exists = "overwrite_terragrunt" }
config = {
bucket = "ecomarket-tfstate-${local.account}"
# During the migration: the INHERITED key, as it is.
# Once verified, it will be changed to the new scheme with a
# deliberate `terraform init -migrate-state` (step 7).
key = "ecomarket/${local.environment}/${local.component}/terraform.tfstate"
region = local.region
encrypt = true
use_lockfile = true
}
}# ---------- STEP 3: migrate ONE component of ONE environment ----------
# Start with network, in dev. The component with the fewest dependencies
# in the environment where a mistake costs least.
mkdir -p live/eu-west-1/dev/network
# Write its terragrunt.hcl with include + inputs (the dev.tfvars values)
cd live/eu-west-1/dev/network
terragrunt init
terragrunt plan# ---------- STEP 4: THE VERIFICATION ----------
# The only thing that matters in the whole migration.
terragrunt plan -detailed-exitcode
echo "Exit code: $?"
# 0 → no changes. CORRECT, carry on.
# 2 → there are changes. STOP. Something does not match.
# 1 → an error. STOP.If the plan does not come out at zero, the diagnosis is in this table:
| What the plan proposes | Almost certain cause |
|---|---|
| Creating EVERYTHING (dozens of resources) | The state key does not match: it points at an empty state |
| Modifying tags on every resource | The generated default_tags differs from the previous one |
| Replacing some resource | An input with a different value from the original .tfvars |
| Changing a few attributes | A value in inputs mistranscribed from dev.tfvars |
| An unconfigured-provider error | The generate "provider" does not cover an alias the module uses |
# A diagnostic tool: compare what Terragrunt resolves
# with what was in the original .tfvars.
terragrunt render-json --terragrunt-json-out /tmp/resolved.json
jq '.inputs' /tmp/resolved.json | sort > /tmp/new.txt
# and contrast it by hand with environments/dev.tfvars# ---------- STEPS 5 and 6: extend ----------
# 5. The other dev components, in order: data, then app.
# When you get to `app`, replace its `terraform_remote_state` blocks with
# `dependency` and verify a zero plan again.
#
# 6. Repeat in staging (after 48 h of stable dev) and then in prod,
# in a window and with the team available. ALWAYS a zero plan.
# ---------- STEP 7 (OPTIONAL, and separate): unify the keys ----------
# Only once EVERYTHING is migrated and stable for weeks.
# Changing `key` to "${path_relative_to_include()}/terraform.tfstate"
# MOVES the state to another path in the bucket: it is a real state
# migration, with -migrate-state, and it deserves its own PR and window.
terragrunt init -migrate-state
terragrunt plan -detailed-exitcode # at zero, againStep 7 is the one most people get wrong. Changing the key scheme looks cosmetic and it moves the state file. If it is done in the same PR as the migration, a failure leaves you unable to tell whether the problem is Terragrunt or the new path. Kept separate, each step has only one possible cause.
Coexistence during the migration
For weeks infra/ (plain Terraform) and live/ (Terragrunt) will coexist. That is normal and manageable with three rules:
- A component lives in one place or the other, never both. Two configurations pointing at the same state is the recipe for the second destroying what the first created.
- The
.gitignoreand theCODEOWNERScover both trees from day one. - The pipeline knows which is which. A script that detects whether the directory has a
terragrunt.hcland picks the command:
#!/usr/bin/env bash
# ci/plan.sh — works with both, during the coexistence period.
set -euo pipefail
DIR="${1:?Usage: ci/plan.sh <directory>}"
if [[ -f "${DIR}/terragrunt.hcl" ]]; then
terragrunt -chdir="${DIR}" plan -out=plan.tfplan
else
ENVIRONMENT="${2:?With plain Terraform the environment is required}"
terraform -chdir="${DIR}" init -reconfigure -backend-config="../../backends/${ENVIRONMENT}.hcl"
terraform -chdir="${DIR}" plan -var-file="../../environments/${ENVIRONMENT}.tfvars" -out=plan.tfplan
fiCommon Errors and Tips
Adopting it because it is fashionable rather than because of a measured symptom. It is the most expensive error, because the cost is permanent and the benefit non-existent if there was no real duplication. Tip: before adopting it, count how many backend.tf files you have and how many incidents that duplication has caused. If the answer is «four and none», do not adopt it.
Putting apply in mock_outputs_allowed_terraform_commands. It is the most dangerous error in the lesson: it allows creating resources pointing at vpc-0000000000000000, which either does not exist or belongs to somebody else. Mocks are for planning, never for applying.
Changing the state key scheme in the same step as the migration. They are two independent changes and one of them moves the state file. Tip: migrate keeping the exact key, verify a zero plan, and unify the paths weeks later, in a PR of its own with -migrate-state.
Not versioning .terragrunt-version. Different Terragrunt versions generate different configuration. It is the same reasoning as .terraform-version and it is forgotten just as easily.
Forgetting .terragrunt-cache/ in the .gitignore. It contains downloaded modules, the .terraform/ directory with its binaries and the generated files. It can take up hundreds of megabytes and, worse, the generated files may contain resolved values.
Using run-all apply as a daily operation. It touches dozens of components at once, the opposite of the contained blast radius that justified separating states. Tip: run-all plan to see the picture, run-all apply only to build a new environment, and individual terragrunt apply day to day.
Generating required_providers without deciding what happens to the lock file. If the lock is generated in the temporary directory, the supply-chain defence from 07-04 §15 is lost. Tip: leave required_providers inside the versioned module, or use copy_terraform_lock_file, but take the decision consciously.
Parsing the path with split("/", ...) to deduce region and environment. It works until somebody adds a level to the tree, and then it fails opaquely. Tip: region.hcl and environment.hcl with read_terragrunt_config.
Putting business logic in the terragrunt.hcl. It is HCL and it is tempting. But every conditional there is logic that is not in the module, that cannot be tested with terraform test (07-03) and that no plan policy can see. Tip: the terragrunt.hcl says which module and with what values; the logic lives in the module.
Believing that Terragrunt solves security or quality. It does not touch the permissions, the state or the quality of the modules. An insecure repository wrapped in Terragrunt is still insecure, with fewer repeated files.
Not writing the ADR. In two years' time somebody will ask why there is an extra layer, and the answer must be a document with the measured symptoms and the alternatives evaluated.
Exercises
Exercise 1: deciding whether to adopt it
Three teams ask for your opinion. For each one: recommend an option from section 16, justify it with at least three concrete criteria, and say what measured symptom would make you change your mind.
-
A. Four people, one product, three environments in a single region, three components (9 roots). Two-minute
apply. Onebackend.tfper root, all correct. Nobody has ever had a problem because of it. Somebody has read an article about Terragrunt and is proposing a migration. -
B. Fifteen people, three environments × four regions × five components (60 roots). Over six months: two incidents from out-of-sync
backend.tffiles (one of them, two regions sharing state) and a half-abandoned provider upgrade that left the repository with three different versions. A mature GitHub Actions pipeline with OIDC, Conftest policies, a nightly drift plan. -
C. Eight people, two environments, two regions, four components (16 roots). They have no pipeline: they apply from their laptops with static keys. The backend is duplicated and out of sync. They want to «fix the mess» and have heard of Terragrunt and of HCP Terraform.
Exercise 2: writing the configuration
EcoMarket adds the eu-central-1 region (Frankfurt) with the three environments and the three components. The data:
- Base CIDR:
10.50.0.0/16. Zones:eu-central-1a,eu-central-1b,eu-central-1c. - Accounts:
dev→123456789012,staging→123456789013,prod→123456789014. - The region's domain:
de.ecomarket.example.com. - Sizing:
dev→db.t3.micro, no NAT, no Multi-AZ, retention 0.prod→db.t3.medium, with NAT, Multi-AZ, retention 30, deletion protection. appdepends onnetworkand ondata;datadepends onnetwork.
You are asked to:
- The
live/eu-central-1/region.hcland thelive/eu-central-1/prod/environment.hcl. - The
live/_envcommon/data.hcl, with itsdependencyand its correctmock_outputs. - The
terragrunt.hclfiles foreu-central-1/prod/network,.../dataand.../app. - The exact commands to deploy the whole region from scratch, in order, and what you verify after each one.
Exercise 3: diagnosing a migration that is going wrong
A colleague is migrating infra/app for staging to Terragrunt. Their terragrunt.hcl:
include "root" {
path = find_in_parent_folders()
}
terraform {
source = "../../../../modules/app"
}
dependency "network" {
config_path = "../network"
mock_outputs = {
vpc_id = "vpc-00000000"
subnets = {}
web_sg_id = "sg-00000000"
}
mock_outputs_allowed_terraform_commands = ["plan", "apply", "validate"]
}
inputs = {
base_name = "ecomarket-staging"
vpc_id = dependency.network.outputs.vpc_id
subnets = dependency.network.outputs.subnets
web_class = "t3.small"
}And the root terragrunt.hcl generates the state key as "${path_relative_to_include()}/terraform.tfstate". The component's current state is at ecomarket/staging/app/terraform.tfstate and the new directory is live/eu-west-1/staging/app.
terragrunt plan proposes creating 23 resources and destroying 0.
You are asked to:
- Explain exactly why the plan proposes creating 23 resources, and what would have happened had they run
apply. - Identify three other problems in the file, one of them serious.
- Rewrite the
terragrunt.hclcorrectly for the migration phase. - Write the complete verification procedure, including what to do if the plan still does not come out at zero.
Solutions
Solution 1
Team A: adopt nothing.
| Criterion | Assessment |
|---|---|
| Number of combinations | 9 roots is below the decision tree's threshold of 10. The duplication exists and is manageable |
| Measured symptoms | None. «Every backend.tf is correct» and «nobody has ever had a problem» is the decisive piece of data |
| Team size | Four people: every training cost is shared between few and every indirection is suffered by all |
| The real motivation | An article. That is the worst possible reason for an architectural decision that is expensive to reverse |
What I would recommend, because it costs little and pays off immediately: consolidate the backend.tf into a partial configuration with -backend-config (07-01 §6.1), if it is not already, and a shared ci/plan.sh. That removes a good part of the duplication with no new dependency at all.
The symptom that would make me change: two more regions arriving (9 → 27 roots), or the first real incident from drift. One of the two, not a forecast.
Team B: Terragrunt, with an ADR.
| Criterion | Assessment |
|---|---|
| Number of combinations | 60 roots. Far above the threshold |
| Measured symptoms | Two incidents in six months, one with two regions sharing state. This is not a hypothesis: it is symptom 1 from section 1, having actually happened |
| Duplication with a demonstrated cost | The half-abandoned provider upgrade is symptom 2: 60 edits are so costly that they do not get done |
| Pipeline maturity | They already have OIDC, Conftest and a drift plan. Terragrunt fits on top without changing any of that, which rules out HCP Terraform as a replacement for machinery that already works |
| Order dependencies | Five components imply an order of application. dependency and run-all solve it; a home-made generator does not |
The ADR must record the concrete data — 60 roots, two incidents with dates, the abandoned upgrade — and the alternatives rejected with their reasons: HCP Terraform because it would duplicate a platform that already works and would add a per-resource cost; home-made generation because it solves neither the chaining nor the order.
The symptom that would make me reconsider: that after six months Terragrunt's error messages are costing more time than the deduplication saves, measured in incident resolution time.
Team C: neither of the two. First, the pipeline.
This is the important answer in the exercise, because the wording invites you to pick a tool and the correct choice is not to pick one yet.
| Stated problem | Severity | Does Terragrunt solve it? |
|---|---|---|
| They apply from their laptops | CRITICAL | No |
| Long-lived static keys | CRITICAL | No |
| No pipeline, no automated review, no policies | HIGH | No |
| Duplicated, out-of-sync backend | Medium | Yes |
The first three problems belong to 07-04 and Terragrunt touches none of them. With 16 roots, the backend duplication is the least of their problems, and adopting a new layer now means learning a tool while the real problem — production credentials on laptops — remains open.
The correct order:
- A pipeline with OIDC and the withdrawal of the static keys (07-04 §4, exercise 3). Weeks 1–4.
- A partial backend with
-backend-config(07-01 §6.1). It solves the drift with no new dependency. Week 5. - Policies and analysis in the PR (07-04 §12). Weeks 6–8.
- And then, if with 16 roots the duplication still hurts, evaluate Terragrunt with data.
And one alternative worth evaluating here and not in the other cases: HCP Terraform. A team with no pipeline, no credential management and no policies gets, all at once, managed state, remote runs with credentials that never touch a laptop, approvals, auditing and Sentinel. In exchange for money and for being tied to the platform. For team C it is a serious option precisely because they do not have the machinery HCP Terraform would replace (08-04).
The symptom that would make me change: none yet. The Terragrunt conversation resumes once the three critical problems are closed.
Solution 2
1. The level configuration files.
# live/eu-central-1/region.hcl
locals {
region = "eu-central-1"
zones = ["eu-central-1a", "eu-central-1b", "eu-central-1c"]
# 10.50.0.0/16: it does not overlap with Ireland (10.20), Paris (10.30)
# or Milan (10.40). The addressing plan is global and lives
# documented in docs/architecture.md.
cidr_base = "10.50.0.0/16"
domain = "de.ecomarket.example.com"
# The KMS key is per region: a key is not used outside its
# own. ACCOUNT is substituted by the root with the environment's account.
kms_key_arn = "arn:aws:kms:eu-central-1:ACCOUNT:key/de-0000-0000"
}# live/eu-central-1/prod/environment.hcl
locals {
environment = "prod"
account = "123456789014"
profile = "high-availability"
# Values common to ALL the components in this environment.
# Per-component sizing goes in the corresponding leaf.
protect_deletion = true
retention_days = 30
create_nat = true
multi_az = true
}2. The data component's common configuration.
# live/_envcommon/data.hcl
# Shared by the 12 region-and-environment combinations.
locals {
cfg_region = read_terragrunt_config(find_in_parent_folders("region.hcl"))
cfg_environment = read_terragrunt_config(find_in_parent_folders("environment.hcl"))
region = local.cfg_region.locals.region
environment = local.cfg_environment.locals.environment
}
terraform {
# An EXACT version: there is no lock file for modules (07-04 §15).
source = "git::[email protected]:ecomarket/terraform-aws-ecomarket-data.git//?ref=v3.1.0"
}
dependency "network" {
config_path = "../network"
mock_outputs = {
vpc_id = "vpc-00000000000000000"
private_subnets = {
"zone-a" = { id = "subnet-00000000000000001", cidr = "10.0.1.0/24", zone = "zone-a" }
"zone-b" = { id = "subnet-00000000000000002", cidr = "10.0.2.0/24", zone = "zone-b" }
}
web_sg_id = "sg-00000000000000000"
}
# WITHOUT `apply`. A mock in an apply would create the database in a
# non-existent VPC or, worse, in somebody else's.
mock_outputs_allowed_terraform_commands = ["plan", "validate", "destroy", "refresh"]
}
inputs = {
base_name = "ecomarket-${local.environment}"
# The dependency's outputs replace the terraform_remote_state.
vpc_id = dependency.network.outputs.vpc_id
subnets = dependency.network.outputs.private_subnets
web_sg_id = dependency.network.outputs.web_sg_id
# Common to every environment: non-negotiable.
storage_encrypted = true
kms_key_arn = replace(
local.cfg_region.locals.kms_key_arn, "ACCOUNT", local.cfg_environment.locals.account,
)
manage_master_user_password = true # pattern B from 07-04 §7
enable_logs = true
# The environment's default values; the leaf can fine-tune them.
high_availability = local.cfg_environment.locals.multi_az
retention_days = local.cfg_environment.locals.retention_days
protect_deletion = local.cfg_environment.locals.protect_deletion
}3. The three leaves of eu-central-1/prod.
# live/eu-central-1/prod/network/terragrunt.hcl
include "root" {
path = find_in_parent_folders()
}
include "envcommon" {
path = "${dirname(find_in_parent_folders())}/_envcommon/network.hcl"
merge_strategy = "deep"
}
inputs = {
# Production uses the region's full CIDR and all three zones.
subnet_bits = 8
}# live/eu-central-1/prod/data/terragrunt.hcl
include "root" {
path = find_in_parent_folders()
}
include "envcommon" {
path = "${dirname(find_in_parent_folders())}/_envcommon/data.hcl"
merge_strategy = "deep"
}
inputs = {
# The only thing specific to this combination: the sizing.
db_class = "db.t3.medium"
storage_gb = 100
max_storage_gb = 400
}# live/eu-central-1/prod/app/terragrunt.hcl
include "root" {
path = find_in_parent_folders()
}
include "envcommon" {
path = "${dirname(find_in_parent_folders())}/_envcommon/app.hcl"
merge_strategy = "deep"
}
inputs = {
web_class = "t3.medium"
min_instances = 3 # one per zone
max_instances = 12
}Each leaf is between 10 and 14 lines, and all the dependencies, the backend, the provider and the encryption are resolved by inheritance.
4. Deploying the region from scratch.
cd live/eu-central-1/prod
# --- STEP 0: verify the identity BEFORE anything else. ---
aws sts get-caller-identity --query Account --output text
# It must return 123456789014. If not, export AWS_PROFILE=ecomarket-prod.
# The before_hook from section 13 checks it anyway, but
# verifying beforehand saves a cycle.
# --- STEP 1: see the full plan, with mocks. ---
# No component is applied, so data and app will use
# mocks for the vpc_id. The plan for those two is INDICATIVE.
terragrunt run-all plan
# VERIFY: the order shown is network → data → app, and the plan for
# `network` (which uses no mocks) is exact and makes sense.
# --- STEP 2: apply the network ON ITS OWN. ---
cd network
terragrunt apply
# VERIFY:
terragrunt output vpc_id # returns a real vpc-
terragrunt output private_subnets # 3 entries, 3 different zones
aws ec2 describe-vpcs --filters "Name=tag:Project,Values=ecomarket" \
--query 'Vpcs[].{Id:VpcId,Cidr:CidrBlock}' # CIDR 10.50.0.0/16
# --- STEP 3: the data. Now it uses network's REAL outputs. ---
cd ../data
terragrunt plan # VERIFY: vpc-00000000000000000 no longer appears
terragrunt apply
# VERIFY:
terragrunt output db_endpoint # ...eu-central-1.rds.amazonaws.com
aws rds describe-db-instances --db-instance-identifier ecomarket-prod-db-XXXX \
--query 'DBInstances[0].{Encrypted:StorageEncrypted,MultiAZ:MultiAZ,Retention:BackupRetentionPeriod}'
# Encrypted: true, MultiAZ: true, Retention: 30
# --- STEP 4: the application. ---
cd ../app
terragrunt plan # VERIFY: no mocks; db_endpoint is the real one
terragrunt apply
# VERIFY:
terragrunt output endpoints
curl -sf https://de.ecomarket.example.com/health
# {"status":"ok"} ← the health check from 06-05
# --- STEP 5: global verification. ---
cd ..
terragrunt run-all plan -detailed-exitcode
# It must come out at ZERO in all three components. A plan that does not come
# out at zero right after applying means a non-deterministic value
# (07-03 §13: the problem ApplyAndIdempotent detects).
# And check the generated state keys: one per component,
# none shared. It is symptom 1 from section 1, verified.
aws s3 ls s3://ecomarket-tfstate-123456789014/eu-central-1/prod/ --recursive
# eu-central-1/prod/network/terraform.tfstate
# eu-central-1/prod/data/terraform.tfstate
# eu-central-1/prod/app/terraform.tfstateWhy run-all apply is not used here, even though it is the use case it was designed for: this is production. Deploying component by component lets you verify each layer before carrying on, and stop the operation if something does not add up without having touched the following ones. run-all apply would be reasonable for creating the whole of eu-central-1/dev in one go.
Solution 3
1. Why it proposes creating 23 resources.
The state key does not match. The root terragrunt.hcl generates:
And this component's real state is at:
They are different paths inside the same bucket. Terragrunt generates a backend.tf pointing at a key that does not exist, S3 returns «no such object», and Terraform interprets that as an empty state: no managed resources. It compares the code (23 declared resources) with the state (empty) and concludes that everything has to be created.
The 0 destructions confirm the diagnosis: if the state were the right one but the inputs were wrong, there would be modifications or replacements. «Create everything, destroy nothing» is the unmistakable signature of a state that cannot be found.
What would have happened with apply. A disaster on three levels, and the second is the worst:
- A second copy of the whole of
staging's infrastructure would be created: another load balancer, another autoscaling group with its instances, another certificate. Immediate doubled cost. - Some resources would fail because of a name conflict — the
ecomarket-staging-albload balancer already exists — leaving theapplyhalf-done: some resources created, others not, and a new partial state. Now there are two states that both believe they own overlapping parts of the same infrastructure, which is the worst possible situation and the hardest to undo (09-03). - The old state would still exist at
ecomarket/staging/app/, pointing at the original resources. The old pipeline's firstapplywould try to reconcile and could destroy what has just been created.
2. The other three problems.
Problem A (SERIOUS): apply in mock_outputs_allowed_terraform_commands.
If network is not applied, a terragrunt apply of app would create the resources using vpc_id = "vpc-00000000". Two outcomes, both bad: either that VPC does not exist and the error arrives halfway through the apply with resources already created, or it does exist — it is a real VPC in another account or belonging to another team — and EcoMarket resources are created inside somebody else's infrastructure.
It is the most dangerous error in the whole lesson, and here it is combined with an empty subnets = {} that would also make the subnet group fail with an incomprehensible error.
Problem B: a source with a relative local path.
Three drawbacks, in order of seriousness:
- It is not versioned. A change in
modules/appaffectsstagingandprodat the same instant, with no promotion and none of the discipline from 04-05. The whole promotion-by-version mechanism from 07-02 §6 is lost. - It is fragile. Four
../depend on the exact depth of the tree. Adding a level breaks it. The robust form is"${get_repo_root()}/modules/app". - It is inconsistent with
dataandnetwork, which in the_envcommonuse published modules with?ref=.
Problem C: it does not use _envcommon, and therefore duplicates.
The file declares terraform, dependency and common inputs (base_name) directly. That means the other 11 combinations will have to repeat the same dependency block with the same mocks. It is exactly symptom 3, the one the migration was meant to eliminate, reproduced in the new tool.
And two minor problems: the data dependency is missing (app needs it according to EcoMarket's architecture), and base_name is hard-coded as "ecomarket-staging" instead of being derived from environment.hcl, which guarantees that sooner or later somebody will copy this file to prod and leave the string behind.
3. The corrected file for the migration phase.
First, the root must keep the inherited key while the migration lasts:
# live/terragrunt.hcl — DURING THE MIGRATION
locals {
cfg_environment = read_terragrunt_config(find_in_parent_folders("environment.hcl"))
cfg_region = read_terragrunt_config(find_in_parent_folders("region.hcl"))
environment = local.cfg_environment.locals.environment
account = local.cfg_environment.locals.account
region = local.cfg_region.locals.region
# The last path segment is the component: network | data | app.
component = basename(get_terragrunt_dir())
}
remote_state {
backend = "s3"
generate = { path = "backend.tf", if_exists = "overwrite_terragrunt" }
config = {
bucket = "ecomarket-tfstate-${local.account}"
# MIGRATION: it reproduces EXACTLY the key that already exists.
# Unifying to path_relative_to_include() is step 7, separately,
# with -migrate-state and its own PR.
key = "ecomarket/${local.environment}/${local.component}/terraform.tfstate"
region = local.region
encrypt = true
use_lockfile = true
}
}And the leaf, leaning on _envcommon:
# live/eu-west-1/staging/app/terragrunt.hcl — CORRECTED
include "root" {
path = find_in_parent_folders()
}
# What is common (source, dependency, shared inputs) lives ONCE.
include "envcommon" {
path = "${dirname(find_in_parent_folders())}/_envcommon/app.hcl"
merge_strategy = "deep"
}
inputs = {
# ONLY what is specific to this combination.
web_class = "t3.small"
min_instances = 2
max_instances = 4
}# live/_envcommon/app.hcl — where everything shared lives.
locals {
cfg_environment = read_terragrunt_config(find_in_parent_folders("environment.hcl"))
environment = local.cfg_environment.locals.environment
}
terraform {
# A published, versioned module, like the other components.
# During the migration it can be "${get_repo_root()}/modules/app"
# if the module is not published yet, but NEVER "../../../../".
source = "git::[email protected]:ecomarket/terraform-aws-ecomarket-app.git//?ref=v3.6.2"
}
dependency "network" {
config_path = "../network"
mock_outputs = {
vpc_id = "vpc-00000000000000000"
private_subnets = {
"zone-a" = { id = "subnet-00000000000000001", cidr = "10.0.1.0/24", zone = "zone-a" }
"zone-b" = { id = "subnet-00000000000000002", cidr = "10.0.2.0/24", zone = "zone-b" }
}
web_sg_id = "sg-00000000000000000"
}
# WITHOUT `apply`. Corrected.
mock_outputs_allowed_terraform_commands = ["plan", "validate", "destroy", "refresh"]
}
# It was missing entirely: app needs the database endpoint.
dependency "data" {
config_path = "../data"
mock_outputs = {
db_endpoint = "mock.eu-west-1.rds.amazonaws.com:5432"
secret_arn = "arn:aws:secretsmanager:eu-west-1:000000000000:secret:mock"
images_bucket = "mock-bucket"
}
mock_outputs_allowed_terraform_commands = ["plan", "validate", "destroy", "refresh"]
}
inputs = {
# Derived, not hard-coded: that way copying the file to another
# environment does not drag the wrong string along.
base_name = "ecomarket-${local.environment}"
vpc_id = dependency.network.outputs.vpc_id
subnets = dependency.network.outputs.private_subnets
web_sg_id = dependency.network.outputs.web_sg_id
db_endpoint = dependency.data.outputs.db_endpoint
db_secret_arn = dependency.data.outputs.secret_arn
images_bucket = dependency.data.outputs.images_bucket
}4. The verification procedure.
# --- STEP 1: a backup. Before touching anything. ---
terraform -chdir=infra/app init -reconfigure \
-backend-config=backends/staging.hcl
terraform -chdir=infra/app state pull > backup-app-staging-$(date +%F).tfstate
jq '.resources | length' backup-app-staging-*.tfstate # 23, confirmed
# --- STEP 2: the EXACT key that has to be reproduced. ---
jq -r '.backend.config.key' infra/app/.terraform/terraform.tfstate
# ecomarket/staging/app/terraform.tfstate
# --- STEP 3: verify that Terragrunt generates THAT key. ---
cd live/eu-west-1/staging/app
terragrunt render-json --terragrunt-json-out /tmp/resolved.json
jq -r '.remote_state.config.key' /tmp/resolved.json
# IT MUST SAY: ecomarket/staging/app/terraform.tfstate
# If it says anything else, STOP HERE. Do not run plan until it matches.
# --- STEP 4: the init and the plan. ---
terragrunt init
terragrunt plan -detailed-exitcode
echo "code: $?"
# 0 → no changes. CORRECT.
# 2 → there are changes. Diagnosis below.What to do if the plan still does not come out at zero:
# First confirm that the state has been found. It is the question
# that separates "it cannot find the state" from "the inputs do not match".
terragrunt state list | wc -l
# 23 → the state HAS BEEN FOUND. The problem is the inputs.
# 0 → it still cannot find it. The key or the bucket is wrong.| Plan symptom | Cause | Fix |
|---|---|---|
state list gives 0 and it proposes creating everything |
The key or the bucket still does not match | Go back to step 3. Check the account in the bucket name too |
| It modifies tags on all 23 resources | The generated default_tags differs from the old providers.tf |
Compare the two tag maps character by character |
It replaces some resource (forces replacement) |
An input with a different value from the original staging.tfvars |
jq '.inputs' /tmp/resolved.json and contrast with the .tfvars |
| It modifies a few attributes | A mistranscribed value, or a different module default | The same as the previous one |
| Error: provider not configured | The module uses an alias generate "provider" does not cover |
Add the alias block to the generate |
Error resolving dependency |
../network is not migrated yet or has no outputs |
Migrate network first. The order matters |
# --- STEP 5: only with a ZERO plan, remove the old directory. ---
git rm -r infra/app
git commit -m "migrate infra/app for staging to Terragrunt
Plan verified at zero. State not moved: the generated key
reproduces ecomarket/staging/app/terraform.tfstate.
Unifying the keys goes in a later PR."The rule that sums up the whole solution: the zero plan is not just another check, it is the check. A plan proposing to create 23 resources in a migration that should create nothing is an unmistakable sign that something is wrong, and the only correct route is to stop and diagnose. Carrying on «to see if it sorts itself out» is how the state incidents that fill module 9 come about.
Conclusion
Terragrunt is a thin wrapper around Terraform that solves two specific problems — scaffolding duplication and orchestration between components — and no others.
- The problem is real and it is measured. Going from 3 environments to 12 means 36 roots, 36
backend.tffiles, 36providers.tffiles, 24terraform_remote_stateblocks and anapplyorder somebody remembers. The four symptoms in section 1 are what justify the conversation. - It is not a replacement for Terraform, nor a new language, nor a state manager. It reads
terragrunt.hcl, generates configuration, resolves dependencies and invokesterraformin a temporary directory. Your modules do not change by a single line. remote_state+generate+path_relative_to_include()solve the out-of-syncbackend.tfat the root: the state key is derived from the directory path, so nobody can write it wrongly.generate "provider"also solves the inability to select a provider instance dynamically that 06-01 pointed out: each root generates its own block with the region and the role already substituted, with no aliases and no conditionals.includewithfind_in_parent_folders()establishes a three-level inheritance: root (backend and provider),_envcommonper component (module and common inputs) and leaf (sizing only). 36 roots of thirteen lines, four common configuration files.- Configuration by levels with
region.hclandenvironment.hclis more robust than parsing the path withsplit: the data lives where it is read, structural changes do not shift indices and each file is reviewable withCODEOWNERS. dependencyreplacesterraform_remote_stateand supplies the order. Themock_outputsallow planning before applying, andapplymust never be inmock_outputs_allowed_terraform_commands: a fake value in an apply creates resources in a non-existent or somebody else's VPC.run-allwalks the graph, parallelises what is independent and destroys in reverse order. And it is a construction tool, not an operations one: day to day it is stillterragrunt applyon one component with its plan reviewed.- What it does NOT solve matters more than what it does: it does not touch the blast radius, nor the duration of a component's
apply, nor drift, nor security, nor policies, nor tests, nor module quality. All of module 7 still applies unchanged. - The cost is real and permanent: one more dependency with its breaking changes, a layer of indirection that has to be learned, error messages coming from three different places, and fewer people who know it.
- There are five alternatives, and the first is to do nothing. HCP Terraform if you do not have the machinery; your own generation if the problem is only the backend; CDKTF if the team prefers a programming language; Terragrunt if there is measured duplication and order dependencies.
- The honest recommendation: do not adopt it if directories and
.tfvarsfiles are enough for you. The threshold is a measured symptom — a real incident from drift, an upgrade abandoned because it was too costly — not a growth forecast. - The migration does not touch the state, and that is why it is safe if it is done properly: a backup, note the exact key, reproduce it as it is, verify a zero plan, extend component by component and environment by environment, and leave the key unification for a later PR with
-migrate-state.
And with that, module 7 comes to an end. Looking back: code organisation, with the three decisions people confuse and the four strategies compared — the conversation 06-01 left half-finished, now complete; version control applied to infrastructure, with what must never go into Git, the emergency procedure for when it is already too late, promotion as a change of reference and the checklist for reviewing a plan that touches production; testing with terraform test and expect_failures, which protects the conditions you wrote in module 6 and lets you refactor a published module without fear; security, with the threat model, Terraform's identity, the four rules of secrets and the Rego policies that really are controls because they live where whoever makes the change cannot switch them off; and Terragrunt, which closes the last open question.
This whole module shares one condition worth stating bluntly as we close it: nothing you have seen here is reliable while it depends on somebody remembering. A terraform fmt that sometimes runs produces diffs full of noise. A tflint that runs when somebody remembers detects nothing on the day it matters. A terraform test suite that is only launched before tagging lets months of regressions through. A Conftest policy that has to be invoked by hand is not a control, it is a document. And a plan the reviewer has to generate themselves ends up being a PR approved with no plan on a Friday afternoon. Formatting, linters, tests, scanners, policies and the plan on the pull request are only worth anything when a machine runs them, on every change, with no exceptions and with nobody able to skip them.
Module 8, Terraform in CI/CD, builds exactly that machine. You will start with the principles of integration — what gets automated and what does not, why plan and apply are separate jobs with separate permissions, how the plan is posted on the pull request and how approvals and protected environments are managed; you will see the same flow implemented with Jenkins and with GitHub Actions, with the OIDC from 07-04 finally configured end to end; then HCP Terraform and Enterprise, which replaces a good part of that machinery with a managed service and where Sentinel goes from an overview to the detail; and finally Atlantis and GitOps flows, where terraform plan stops being a command somebody runs and becomes a PR comment.
