patternbashterraformTip
Terragrunt provides DRY remote state configuration and multi-account Terraform at scale
Viewed 0 times
Terragrunt >= 0.55 required for modern include syntax
terragruntDRYremote statebackendmulti-accountpath_relative_to_includerun-alldependency blocks
Problem
Large Terraform codebases repeat the same backend configuration (S3 bucket, DynamoDB table, region) in every module directory. Managing dozens of modules with slightly different configurations leads to copy-paste drift and makes bulk changes (like rotating the state bucket) painful.
Solution
Use Terragrunt to define backend configuration once in a root
Root
Child
terragrunt.hcl and inherit it in every child module directory. Terragrunt generates the backend block dynamically and handles the unique state key per directory.Root
terragrunt.hcl:remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite"
}
config = {
bucket = "my-tfstate-${local.account_id}"
key = "${path_relative_to_include()}/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-state-lock"
}
}Child
services/api/terragrunt.hcl:include "root" {
path = find_in_parent_folders()
}
terraform {
source = "../../../modules/api"
}
inputs = {
environment = "prod"
instance_type = "m5.large"
}Why
Terragrunt treats infrastructure as a graph of dependent modules with shared configuration. It eliminates backend boilerplate, handles dependency ordering with
dependency blocks, and enables run-all commands to apply an entire account or environment.Gotchas
- Terragrunt is a wrapper — it delegates to Terraform, so Terraform must be installed separately (or use tfenv)
- The
path_relative_to_include()function generates a unique S3 key per module directory — do not change directory structure without migrating state - dependency blocks with
mock_outputsallow planning modules before their dependencies are applied - Terragrunt adds complexity — evaluate whether a simpler mono-module approach is sufficient first
Context
Large infrastructure codebases with many Terraform modules sharing the same backend configuration
Revisions (0)
No revisions yet.