Terragrunt

On this page 7

Terragrunt is an open-source orchestration wrapper for Terraform and OpenTofu that keeps configuration DRY (do not repeat yourself) across many environments, accounts and regions. Infrastructure as code projects that grow beyond a single environment tend to duplicate backend settings, provider blocks and module calls; Terragrunt generates those repeated pieces from shared parent files and runs the underlying tool once per unit.

Terragrunt does not replace Terraform. It calls the terraform or tofu binary under the hood, so providers, modules and state formats stay unchanged. Its value lies in structure and orchestration: one small configuration file per deployable unit, explicit dependencies between units and commands that run across a whole directory tree.

How Terragrunt wraps Terraform and OpenTofu

Terragrunt reads a configuration file named terragrunt.hcl in each unit directory, prepares a working copy of the referenced module and then invokes the real Terraform or OpenTofu command with generated files and arguments. The configuration language is HCL, the same syntax used by HashiCorp Configuration Language files, extended with Terragrunt-specific blocks and functions.

A typical run follows a fixed sequence. Terragrunt resolves includes from parent folders, downloads the module named in the terraform block’s source attribute into a local cache directory, writes generated files such as backend.tf and provider.tf, passes the inputs as TF_VAR environment variables and finally executes plan, apply or any other command the user requested.

The following table lists the core configuration blocks and the duplication each one removes.

Block or attributePurposeDuplication it removes
terraform sourcePoints to a versioned moduleCopy-pasted root modules
remote_stateDefines the state backend oncePer-folder backend blocks
generateWrites provider or version filesRepeated provider settings
includeInherits a parent configurationShared settings per account or region
inputsSets module variablesLong tfvars files per environment
dependencyReads outputs of another unitManual remote state lookups
Core blocks in a terragrunt.hcl file

Repository layout and the unit model

Terragrunt encourages a live repository that mirrors the real topology, for example account/region/environment/component, while reusable code lives in a separate modules repository pinned by Git tags. Each leaf folder is a unit, one deployable piece with its own small Terraform state file, and a group of units forms a stack.

Small, isolated state files are the central design choice. A narrow blast radius means that a faulty apply against the database unit cannot destroy the network unit, and shorter plan times follow because each run refreshes only a few dozen resources instead of thousands. The cost is more state files to manage, which Terragrunt offsets by deriving each backend key automatically from the folder path with path_relative_to_include().

Units reference each other through dependency blocks. Terragrunt builds a directed acyclic graph from those references and, with run --all (formerly run-all), applies units in dependency order, running independent units in parallel and destroying them in reverse order. Mock outputs let a plan proceed when an upstream unit has not been applied yet.

Teams usually choose Terragrunt after weighing it against native Terraform features and other platforms. The comparison below summarizes how each option handles multi-environment code reuse.

ApproachEnvironment separationMain trade-off
Plain Terraform root modulesOne folder per environment with copied codeSimple but highly repetitive
Terraform workspacesSeveral states for one configurationHard to vary settings or accounts per environment
TerragruntOne small file per unit, shared parentsExtra tool and conventions to learn
Terraform stacks or HCP featuresVendor-managed orchestrationTied to a commercial platform
Pulumi or AWS CDKGeneral-purpose programming languagesDifferent ecosystem and state model
Ways to manage many environments

Terragrunt also differs from configuration management tools such as Ansible, Chef or Puppet, which configure software on existing machines. Terragrunt operates strictly at the provisioning layer and inherits the declarative configuration model of Terraform.

Practical configuration and adoption

Successful adoption depends more on conventions than on features. Most teams keep a single root file that defines the remote state and provider generation, a small env.hcl or region.hcl per level read with read_terragrunt_config(), and leaf files that contain only the module source and its inputs.

The following decision table shows common situations and the recommended Terragrunt practice.

SituationRecommended practiceReason
Several AWS accounts per environmentAssume a role in the generated providerCredentials stay outside the code
Shared module used by many unitsPin the source to a Git tagUpgrades roll out environment by environment
Unit needs another unit’s outputsUse a dependency blockOrder and data flow become explicit
Plans in CI for a large treeRun only units changed in the commitShorter pipelines and fewer locks
Migration to OpenTofuSet the binary path to tofuUnits move without code rewrites
Decision table for Terragrunt practices

Terragrunt also adds hooks that run shell commands before or after Terraform, automatic retries for known transient provider errors and an option to create the state bucket and lock table on first use. These features reduce glue scripts in CI pipelines.

Limitations and common mistakes

Terragrunt solves duplication but introduces its own operational complexity. Experienced practitioners watch for the following problems.

SymptomCauseFix
Plan of a downstream unit failsUpstream outputs not yet appliedAdd mock outputs for plan and validate
Deep include chains are unreadableToo many inheritance levelsLimit to root plus one shared level
Run across all units is slowEvery unit initializes providersEnable a shared provider cache
Unexpected changes after an upgradeUnpinned module sourceReference immutable tags or commits
Apply of all units destroys too muchBroad command run from the rootScope runs and review every plan
Frequent Terragrunt problems
  • Configuration drift is not prevented by Terragrunt itself; scheduled plans or policy as code checks are still needed.
  • Learning curve: engineers must understand both Terraform and Terragrunt semantics, including how inputs become variables.
  • Tool versions must be pinned consistently in CI and on workstations, since command names have changed between releases.

In plain words

Terraform is a tool that builds cloud servers, networks and databases from written instructions. When a company runs the same setup for testing, staging and production, those instructions are often copied three times, and every copy must be fixed separately.

Terragrunt works like a master template with small fill-in cards. The shared parts are written once, and each environment keeps only a short card with its differences, such as size or name. Less copying means fewer mistakes and faster, safer changes.

A real-world example

A platform team at a mid-sized software company manages four AWS accounts (development, testing, staging and production) across two regions. Before adopting Terragrunt, each environment had its own copy of about 40 Terraform files, and backend settings differed by mistake in two places.

The team moved reusable code into a versioned modules repository and created a live repository with about 60 units, each defined by a terragrunt.hcl file of 15 to 30 lines. A root file generated the S3 backend and the role-assuming provider for every unit, and dependency blocks connected the network, database and application units.

The result was roughly 70 percent less duplicated code, plans that finished in under two minutes per unit instead of fifteen for the former monolithic state, and module upgrades promoted one environment at a time by changing a single Git tag.