skip to content

In Terragrunt, how do `include` and a shared `root.hcl` keep backend and provider settings DRY, and what do `remote_state` and `generate` each do?

level: middleimportance: must knowfreq 48%

answer

  1. one parent, many units
  2. merged before processing
  3. a path-derived state key
  4. write a file before init
  5. bucket creation is opt-in now

basics

~20 s

Each Terragrunt unit's include block merges a shared root.hcl, so backend and provider settings live once. remote_state configures the backend, with a per-unit key from path_relative_to_include(); generate writes any file, such as provider.tf, before Terraform runs.

solid answer

~30 s

Each unit has `include "root" { path = find_in_parent_folders("root.hcl") }`, which merges the parent into the unit before processing. In `root.hcl`, `remote_state` defines the backend once, and `key = "${path_relative_to_include()}/terraform.tfstate"` gives every unit its own state path; its `generate` map writes `backend.tf` into the working directory. A `generate` block writes any other file, typically `provider.tf`, and can take its region from a `region.hcl` read with `read_terragrunt_config`. Two details trip people up: Terragrunt only creates the state bucket with `--backend-bootstrap` or `terragrunt backend bootstrap`, and an included file cannot itself contain an `include`.

code

hcl · 29 lines
hcl
# live/root.hcl
locals {
  region = read_terragrunt_config(find_in_parent_folders("region.hcl")).locals.region
}

remote_state {
  backend = "s3"
  generate = {
    path      = "backend.tf"
    if_exists = "overwrite_terragrunt"
  }
  config = {
    bucket       = "example-org-tf-state"
    key          = "${path_relative_to_include()}/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

generate "provider" {
  path      = "provider.tf"
  if_exists = "overwrite_terragrunt"
  contents  = <<EOF
provider "aws" {
  region = "${local.region}"
}
EOF
}

go deeper

for a junior

Recall that include pulls a shared file into a unit, and that remote_state and generate are the two ways to avoid repeating backend and provider blocks.

for a middle

Explain how path_relative_to_include() builds a distinct key per unit, what a shallow merge replaces, and why included files cannot include anything further.

for a senior

Mention what the shared file hides: a root.hcl edit changes every unit with no unit diff, renaming a directory moves its state key, and bootstrapping is now opt-in.

for a principal

Weigh one shared root against the blast radius of editing it. Decide who reviews it and how a change rolls through environments, since a single merged edit reaches every unit that includes it.

## The problem a shared file solves Every Terraform root module needs a backend block and usually a provider block. In a repository of many small roots those blocks are nearly identical, and a backend block cannot use input variables to hide the differences. Terragrunt moves them into one parent file, and each **unit** (a directory with a `terragrunt.hcl`) inherits them. ## `include`: merging a parent into a unit An `include` block names a parent file. Terragrunt merges that parent into the unit before processing it. ```hcl # live/prod/us-east-1/vpc/terragrunt.hcl include "root" { path = find_in_parent_folders("root.hcl") } terraform { source = "git::[email protected]:example-org/modules.git//vpc?ref=v1.4.0" } inputs = { cidr = "10.10.0.0/16" } ``` The rules worth knowing: - **`find_in_parent_folders("root.hcl")`** walks upward from the unit and returns the first file with that name. - **Labels are expected.** You may have several `include` blocks, each with a unique label. A bare `include {}` is deprecated. - **`merge_strategy`** is `shallow` by default, with `deep` and `no_merge` as the alternatives. With `shallow`, a value the child sets replaces the parent's, except `dependencies` lists, which are concatenated. - **`expose = true`** lets the child read the parent's data, for example `include.root.locals.bucket`. - **One level only.** Terragrunt errors out if an included file has an `include` block of its own. - **Several parents are fine.** A unit can include `root.hcl` for everything and a second file such as `_env/app.hcl` for what only `app` units share, which is the usual way round the one-level limit. The file is called `root.hcl` because a root file named `terragrunt.hcl` looks like a unit. Terragrunt's migration guide recommends renaming it, and that means passing the name explicitly: with no argument, `find_in_parent_folders()` looks for `terragrunt.hcl`. ## `remote_state` and `generate` | | `remote_state` | `generate` | |---|---|---| | Purpose | Configure the state backend | Write any file into the working directory | | What it writes | A backend file at `generate.path`, typically `backend.tf`, when that map is set | The file at `path`, holding `contents` | | Creates a state bucket | Only with `--backend-bootstrap` or `terragrunt backend bootstrap` | Never | | Typical use | One backend definition for all units | `provider.tf`, or a backend when no bootstrapping is wanted | Use one or the other for the backend, never both. Both accept `if_exists`; `overwrite_terragrunt` replaces a file only if Terragrunt generated it and errors otherwise, and it spots its own files through a signature comment. Without `generate`, a `remote_state` block still works: Terragrunt passes the settings to `init` as `-backend-config` values, and the module needs an empty `backend "s3" {}` block for them to fill. The key line is the state path: `key = "${path_relative_to_include()}/terraform.tfstate"`. `path_relative_to_include()` returns the unit's path relative to the including root, so `live/prod/us-east-1/vpc` stores its state at `prod/us-east-1/vpc/terraform.tfstate`. One definition gives every unit a separate state object. ## Fanning out across regions Regions fit the same mechanism. Put a `region.hcl` holding `locals { region = "us-east-1" }` in each region directory and read it from `root.hcl`: ```hcl locals { region = read_terragrunt_config(find_in_parent_folders("region.hcl")).locals.region } ``` `find_in_parent_folders` runs in the context of the including unit, so a `generate "provider"` block in `root.hcl` writes the right `region` for each unit. There is one provider per unit, with its own state, instead of an aliased provider inside one large root. ## What the shared file costs 1. **A stale assumption about bootstrapping.** `--backend-bootstrap` defaults to `false`. If the bucket does not exist, Terragrunt creates nothing and `init` fails. Older guides describe automatic creation, which is the behaviour the CLI redesign removed. Bootstrapping covers `s3`, `gcs` and `azurerm`. 2. **Changes that a file diff hides.** Editing `root.hcl` affects every unit that includes it, yet no `terragrunt.hcl` shows up in the diff. `--queue-include-units-reading` selects the units that read a given file, and `--working-dir` scopes the roll-out one environment at a time. 3. **State that follows the directory.** Because the key comes from the path, renaming a unit's directory points it at a new, empty state object, and the next plan proposes creating everything. `terragrunt backend migrate old-unit new-unit` exists for this. 4. **A half-finished roll-out.** If you stop rolling out a shared-file change after `qa`, the file now describes a version that `prod` should not get. Terragrunt's guide suggests keeping a copy of the old version and pointing the lagging environments at it.

  • When would you choose `generate` over `remote_state` for the backend?
    When you do not want Terragrunt to bootstrap anything. Terragrunt's docs advise a `generate` block if you do not intend it to create state resources, and for backends other than `s3`, `gcs` and `azurerm`, `remote_state` behaves like `generate` anyway. Pick one for the backend, because using both at once is not allowed.
  • What happens to a unit's state if you rename its directory?
    With a key built from `path_relative_to_include()`, the key changes with the path, so `init` points at an empty state object and the next plan proposes creating everything. Run `terragrunt backend migrate old-unit new-unit` to move the state, then check that the plan shows no changes.
  • A unit needs a value defined in `root.hcl`. How does it read it?
    Set `expose = true` on the `include` block and reference `include.root.locals.<name>`. The merge alone is not enough, because the included data only becomes readable through the `include` variable once it is exposed. `merge_strategy = "no_merge"` reads a file's data without merging its blocks.

  • Terragrunt 1.x creates a missing state bucket automatically on the first run.
  • An included root.hcl can include another file, so parents can form a deep chain.
  • Use a remote_state block and a generate block together on the same backend for safety.
  • Terragrunt gives every unit a separate state even if the key is a fixed string.
  • A unit's state key stays the same when its directory is renamed.