Skip to content
🎉 Terragrunt v1.0 is here! Read the announcement to learn more.

Keep your backend configuration DRY

By The Gruntwork Team

A common source of duplication in OpenTofu/Terraform codebases is the remote state backend block, which has to be repeated in every module. Terragrunt lets you define it once and generate it into every unit.

The pattern

In your root root.hcl, configure the backend and have Terragrunt generate it for each unit:

remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
config = {
bucket = "my-tofu-state"
key = "${path_relative_to_include()}/tofu.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "my-lock-table"
}
}

Each child unit then includes the root configuration:

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

Now every unit writes its state to a unique key derived from its path, and you never repeat the backend configuration.

Why it works

  • path_relative_to_include() gives each unit a distinct state key.
  • generate writes the backend block into the unit at runtime, so OpenTofu/Terraform sees a normal backend configuration.

See State Backend for the full reference.


← Back to all patterns