A Terragrunt setup turns one set of OpenTofu modules into three environments without copying a single backend block. This tutorial builds that setup on AWS in 13 steps and about 70 minutes, and it ends with dev, staging and prod deployed from one repository, one state bucket and one root file. Terragrunt, from Gruntwork, orchestrates Terraform and OpenTofu at scale, and that orchestration is the whole job of this guide.
The timing is good. OpenTofu 1.13.0 shipped on September 29, 2026, and its project says the 1.13 series gets security support through August 2027. That gives you a stable CLI to pin. If you are still deciding between engines, see how OpenTofu stacks up against Terraform and Pulumi before you commit.
Plain OpenTofu works fine for one environment. It starts to hurt at three, because every environment needs its own backend config, its own provider block and its own copy of the same variables. Terraform workspaces on an S3 backend solve part of that, but they share one backend definition and one blast radius. Terragrunt gives each folder its own state file and generates the repeated parts for you.
Why a Terragrunt Setup Still Matters in 2026
Infrastructure as code is now ordinary plumbing. Terraform and OpenTofu are everywhere in AWS shops, and that is why so many teams end up with the same problem: lots of AWS, lots of Terraform-style code, and no clean way to repeat it across environments.
Terragrunt is a thin wrapper that sits in front of your IaC binary. It reads small HCL files, generates backend and provider code, wires outputs from one unit into another, and runs many units in dependency order. It does not replace OpenTofu. It calls it. That separation is why the same layout works whether you run tofu or terraform underneath.
Three facts shape the choices in this tutorial, all current as of November 7, 2026:
- OpenTofu v1.13.0 is the newest confirmed CLI release. It dropped WinRM provisioners and phased out official 32-bit builds, and official macOS builds now need macOS 13 Ventura or later.
- OpenTofu added official Windows ARM64 packages starting with v1.13.0, so Windows on Arm laptops no longer need a workaround.
- A secondary source reports that the legacy HCP Terraform free plan ended on March 31, 2026. Check the syntaqx IaC platforms chapter and HashiCorp’s own pricing page before you plan around any hosted free tier.
One more point on versions. Terragrunt itself reportedly reached a 1.0 release announced on March 30, 2026, but no official release page was retrievable on the day this was written. So the guide never hard-codes a Terragrunt version. You install the latest release, record it with terragrunt --version, and pin it in a tools file. If you are new to the underlying engine, start with setting up Terraform on AWS from scratch and come back.
Prerequisites and Versions to Pin
You need an AWS account where you can create a VPC, security groups and S3 buckets. A personal sandbox account is ideal. AWS’s sign-up page currently advertises $100 in Free Tier credits right away plus up to $100 more as you explore, and this lab fits well inside that. S3 has no minimum charge, and the VPC, subnets, internet gateway and security groups cost nothing to exist. The lab deliberately skips NAT gateways, which bill by the hour. Before you start, put a guardrail in place with AWS Budgets with Terraform or the console equivalent.
| Tool | What to pin | Why |
|---|---|---|
| OpenTofu | 1.13.x | Newest confirmed line, v1.13.0 released September 29, 2026, security support through August 2027 |
| Terragrunt | Latest release from the official docs | Record the exact number with terragrunt --version |
| AWS CLI | Version 2 | Needed for SSO login and the bootstrap commands |
| mise | Latest | Pins OpenTofu and Terragrunt per repository |
| AWS provider | Constraint >= 5.0 |
Loose enough to stay valid, tight enough to avoid ancient releases |
| Operating system | Linux, macOS 13+, or Windows through WSL2 | Official macOS builds require Ventura or later |
| Git | Any current 2.x | You will commit the repo and CI reads it |
Budget about 70 minutes. The first 20 go to installs and credentials, the next 35 to writing files and the first apply, and the last 15 to promotion, CI and cleanup. If a command prints something different from the samples below, trust your terminal and check the troubleshooting table near the end.
What You Will Build
The project has three small modules, three environments and one root config. Each environment holds three units. A unit is a folder with a terragrunt.hcl file, and it owns exactly one state file.
tg-aws-lab/
├── .mise.toml
├── .gitignore
├── root.hcl
├── _envcommon/
│ ├── network.hcl
│ ├── web-sg.hcl
│ └── artifacts.hcl
├── modules/
│ ├── network/ (VPC, 2 public subnets, internet gateway)
│ ├── web-sg/ (security group, port 443 in)
│ └── artifacts/ (versioned, encrypted, private S3 bucket)
└── live/
├── dev/
│ ├── env.hcl
│ └── us-east-1/
│ ├── region.hcl
│ ├── network/terragrunt.hcl
│ ├── web-sg/terragrunt.hcl
│ └── artifacts/terragrunt.hcl
├── staging/ (same shape)
└── prod/ (same shape)
The dependency graph is short on purpose. The web-sg unit needs the VPC ID from network, so Terragrunt must apply network first. The artifacts unit stands alone, so Terragrunt can run it in parallel. Nine units, nine state files, one bucket.
Steps 1-3: Install OpenTofu and Terragrunt, Then Authenticate to AWS
Step 1. Install mise. A version manager keeps the pins in the repository instead of in your head. On Linux, macOS or WSL2 the official install script works. Open a new shell afterwards so the shims load.
curl https://mise.run | sh
echo 'eval "$(~/.local/bin/mise activate bash)"' >> ~/.bashrc
exec bash
mise --version
Prefer Homebrew? brew install opentofu terragrunt also works, but you lose the per-repo pin. For a team, the pin matters more than the install method.
Step 2. Pin OpenTofu 1.13 and the latest Terragrunt. Create the project folder and let mise write the tools file.
mkdir tg-aws-lab && cd tg-aws-lab
git init
mise use opentofu@1.13 terragrunt@latest
tofu version
terragrunt --version
cat .mise.toml
You should see an OpenTofu v1.13.x line and a Terragrunt version. Write the Terragrunt number down. After you confirm it, replace latest in .mise.toml with that exact version so teammates and CI run the same binary. Then add the environment variable that tells Terragrunt to call OpenTofu instead of Terraform.
[tools]
opentofu = "1.13"
terragrunt = "REPLACE_WITH_YOUR_VERSION"
[env]
TG_TF_PATH = "tofu"
Run mise trust once so mise loads the file, then confirm with echo $TG_TF_PATH. It should print tofu. Skip this and Terragrunt hunts for a terraform binary, which is the single most common first-run failure.
Step 3. Authenticate to AWS and prove it. Use SSO or a short-lived profile, never long-lived keys in a file. Pick a profile name, log in, and check which account you are about to touch.
aws configure sso --profile tg-lab
aws sso login --profile tg-lab
export AWS_PROFILE=tg-lab
export AWS_REGION=us-east-1
aws sts get-caller-identity
The last command prints a JSON block with Account, UserId and Arn. Read the account number out loud. Terragrunt will later use get_aws_account_id() to build bucket names, so a wrong profile here creates resources in the wrong place. If you use a plain IAM user, aws configure works the same way, but rotate the key when the lab is over.
Steps 4-6: Smoke Test, Repository Layout and the State Bucket
Step 4. Run a smoke test with no AWS involved. Before you touch the cloud, prove that Terragrunt can drive OpenTofu. The official quick start uses the local provider to write a file, and it needs no credentials. Create a throwaway folder outside the repo.
mkdir -p /tmp/tg-smoke && cd /tmp/tg-smoke
cat > main.tf <<'EOF'
resource "local_file" "file" {
content = "Hello, World!"
filename = "${path.module}/hello.txt"
}
EOF
touch terragrunt.hcl
terragrunt init
terragrunt plan
The empty terragrunt.hcl is enough to mark the folder as a unit. Expect lines prefixed with STDOUT tofu:, which tells you Terragrunt shelled out to OpenTofu. The quick start in the Terragrunt docs shows the same flow, including the provider install message for hashicorp/local v2.5.2 and the plan that creates local_file.file with the content Hello, World!.
STDOUT tofu: Initializing provider plugins...
STDOUT tofu: - Finding latest version of hashicorp/local...
STDOUT tofu: - Installing hashicorp/local v2.5.2...
STDOUT tofu: OpenTofu has been successfully initialized!
STDOUT tofu: OpenTofu will perform the following actions:
STDOUT tofu: # local_file.file will be created
If you see tofu in those prefixes, the toolchain works. If you see terraform, your TG_TF_PATH is not set. Fix that before moving on. Want more practice with OpenTofu on a different target afterwards? Another OpenTofu project in our archive builds a Kubernetes cluster with it. Delete the smoke folder with rm -rf /tmp/tg-smoke and return to the repo.
Step 5. Create the repository skeleton. One command builds every folder. Run it from tg-aws-lab.
cd ~/tg-aws-lab
mkdir -p _envcommon modules/{network,web-sg,artifacts}
for env in dev staging prod; do
mkdir -p live/$env/us-east-1/{network,web-sg,artifacts}
done
cat > .gitignore <<'EOF'
.terragrunt-cache/
.terraform/
*.tfstate
*.tfstate.backup
backend.tf
provider.tf
EOF
find . -type d -not -path './.git*' | sort | head -30
The .gitignore matters. Terragrunt writes backend.tf and provider.tf into every unit at run time, and it parks downloaded module copies in .terragrunt-cache. None of that belongs in Git. Commit the HCL you write, not the files Terragrunt generates.
Step 6. Bootstrap the remote state bucket. Terragrunt can create the backend for you, and recent releases gate that behavior behind a bootstrap option. The exact flag has moved between versions, so this tutorial creates the bucket explicitly. That keeps the guide version-proof and teaches you what a safe state bucket looks like.
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
BUCKET="tg-lab-state-${ACCOUNT_ID}"
aws s3api create-bucket --bucket "$BUCKET" --region us-east-1
aws s3api put-bucket-versioning --bucket "$BUCKET"
--versioning-configuration Status=Enabled
aws s3api put-bucket-encryption --bucket "$BUCKET"
--server-side-encryption-configuration
'{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
aws s3api put-public-access-block --bucket "$BUCKET"
--public-access-block-configuration
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
echo "state bucket: $BUCKET"
Four settings protect the state. Versioning lets you roll back a corrupted file. Default encryption covers secrets that leak into state. The public access block removes any chance of an open bucket. The account ID in the name avoids the global bucket-name collisions that bite everyone who calls a bucket terraform-state. Outside us-east-1 you must add a --create-bucket-configuration LocationConstraint=REGION flag, and the lab stays in us-east-1 to dodge that wrinkle.
Locking deserves a sentence. Current OpenTofu releases support native S3 lock files through use_lockfile = true, so you no longer need a DynamoDB table just for locks. Older guides still show the table. If your engine is older than the 1.13 line this tutorial pins, upgrade instead of bolting the table back on.
Steps 7-8: Write the Root Configuration and the Modules
Step 7. Write root.hcl. This one file replaces nine copies of backend and provider config. Name it root.hcl, not terragrunt.hcl. Terragrunt treats any terragrunt.hcl as a unit, and a root file that looks like a unit causes confusing run-all behavior.
locals {
env_vars = read_terragrunt_config(find_in_parent_folders("env.hcl"))
region_vars = read_terragrunt_config(find_in_parent_folders("region.hcl"))
env = local.env_vars.locals.env
aws_region = local.region_vars.locals.aws_region
account_id = get_aws_account_id()
}
remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
config = {
bucket = "tg-lab-state-${local.account_id}"
key = "${path_relative_to_include()}/tofu.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.aws_region}"
allowed_account_ids = ["${local.account_id}"]
default_tags {
tags = {
Environment = "${local.env}"
ManagedBy = "terragrunt"
Project = "tg-aws-lab"
}
}
}
EOF
}
Read the three pieces in order. The locals block pulls the environment name and region from files that live next to each unit, so the root stays generic. The remote_state block writes a backend.tf for every unit and builds the state key from the unit’s path. That key is what keeps nine states from colliding. The generate block writes the AWS provider with allowed_account_ids, a cheap safety net that makes a wrong-account apply fail before it creates anything.
Step 8. Write the three modules. They are ordinary OpenTofu with no Terragrunt-specific syntax, which is the point. You can run them without Terragrunt if you ever need to. Start with the network module.
# modules/network/main.tf
variable "name" { type = string }
variable "cidr" { type = string }
data "aws_availability_zones" "available" {
state = "available"
}
resource "aws_vpc" "this" {
cidr_block = var.cidr
enable_dns_hostnames = true
tags = { Name = "${var.name}-vpc" }
}
resource "aws_internet_gateway" "this" {
vpc_id = aws_vpc.this.id
tags = { Name = "${var.name}-igw" }
}
resource "aws_subnet" "public" {
count = 2
vpc_id = aws_vpc.this.id
cidr_block = cidrsubnet(var.cidr, 8, count.index)
availability_zone = data.aws_availability_zones.available.names[count.index]
map_public_ip_on_launch = true
tags = { Name = "${var.name}-public-${count.index}" }
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.this.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.this.id
}
tags = { Name = "${var.name}-public" }
}
resource "aws_route_table_association" "public" {
count = 2
subnet_id = aws_subnet.public[count.index].id
route_table_id = aws_route_table.public.id
}
output "vpc_id" { value = aws_vpc.this.id }
output "public_subnet_ids" { value = aws_subnet.public[*].id }
This VPC has public subnets only, which keeps the lab free. For private subnets and NAT, follow our NAT-based VPC build and swap that module in later. Terragrunt will not care. Next, the security group and the bucket.
# modules/web-sg/main.tf
variable "name" { type = string }
variable "vpc_id" { type = string }
variable "ingress_cidrs" { type = list(string) }
resource "aws_security_group" "web" {
name = "${var.name}-web"
description = "HTTPS in, everything out"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "https" {
for_each = toset(var.ingress_cidrs)
security_group_id = aws_security_group.web.id
cidr_ipv4 = each.value
from_port = 443
to_port = 443
ip_protocol = "tcp"
}
resource "aws_vpc_security_group_egress_rule" "all" {
security_group_id = aws_security_group.web.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1"
}
output "security_group_id" { value = aws_security_group.web.id }
# modules/artifacts/main.tf
variable "name" { type = string }
data "aws_caller_identity" "current" {}
resource "aws_s3_bucket" "this" {
bucket = "${var.name}-artifacts-${data.aws_caller_identity.current.account_id}"
}
resource "aws_s3_bucket_versioning" "this" {
bucket = aws_s3_bucket.this.id
versioning_configuration { status = "Enabled" }
}
resource "aws_s3_bucket_server_side_encryption_configuration" "this" {
bucket = aws_s3_bucket.this.id
rule {
apply_server_side_encryption_by_default { sse_algorithm = "AES256" }
}
}
resource "aws_s3_bucket_public_access_block" "this" {
bucket = aws_s3_bucket.this.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
output "bucket_name" { value = aws_s3_bucket.this.bucket }
Finally, give each module a versions.tf so the provider constraint is explicit. The same file goes into all three folders.
for m in network web-sg artifacts; do
cat > modules/$m/versions.tf <<'EOF'
terraform {
required_version = ">= 1.10"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 5.0"
}
}
}
EOF
done
Steps 9-10: Environment Files, Shared Includes and the First Apply
Step 9. Describe dev, then wire its three units. Environment facts live in two tiny files. The first sits at the environment level, the second at the region level. Nothing else in the tree repeats them.
cat > live/dev/env.hcl <<'EOF'
locals {
env = "dev"
vpc_cidr = "10.10.0.0/16"
web_cidrs = ["10.0.0.0/8"]
}
EOF
cat > live/dev/us-east-1/region.hcl <<'EOF'
locals {
aws_region = "us-east-1"
}
EOF
Now the shared includes. An _envcommon file holds what every environment shares for one component, namely the module source and the naming input. Each environment’s unit then includes it and adds only what differs. Write all three.
for c in network web-sg artifacts; do
cat > _envcommon/$c.hcl <<EOF
locals {
env_vars = read_terragrunt_config(find_in_parent_folders("env.hcl"))
env = local.env_vars.locals.env
}
terraform {
source = "${dirname(find_in_parent_folders("root.hcl"))}/modules/$c"
}
inputs = {
name = "tg-lab-${local.env}"
}
EOF
done
cat _envcommon/network.hcl
The backslashes in that loop stop the shell from expanding ${...} while it writes the files, and the unescaped $c becomes the module name. The printed network.hcl should show a clean ${dirname(...)} expression. Now write the dev units. Network and artifacts are short.
# live/dev/us-east-1/network/terragrunt.hcl
include "root" {
path = find_in_parent_folders("root.hcl")
}
include "envcommon" {
path = "${dirname(find_in_parent_folders("root.hcl"))}/_envcommon/network.hcl"
}
locals {
env_vars = read_terragrunt_config(find_in_parent_folders("env.hcl"))
}
inputs = {
cidr = local.env_vars.locals.vpc_cidr
}
# live/dev/us-east-1/artifacts/terragrunt.hcl
include "root" {
path = find_in_parent_folders("root.hcl")
}
include "envcommon" {
path = "${dirname(find_in_parent_folders("root.hcl"))}/_envcommon/artifacts.hcl"
}
The security group unit is where Terragrunt earns its keep. It declares a dependency on network and reads the VPC ID from that unit’s outputs. The mock_outputs block gives validate and plan a placeholder when the network does not exist yet, and the allow-list keeps those fakes away from apply.
# live/dev/us-east-1/web-sg/terragrunt.hcl
include "root" {
path = find_in_parent_folders("root.hcl")
}
include "envcommon" {
path = "${dirname(find_in_parent_folders("root.hcl"))}/_envcommon/web-sg.hcl"
}
locals {
env_vars = read_terragrunt_config(find_in_parent_folders("env.hcl"))
}
dependency "network" {
config_path = "../network"
mock_outputs = {
vpc_id = "vpc-00000000"
}
mock_outputs_allowed_terraform_commands = ["init", "validate", "plan"]
}
inputs = {
vpc_id = dependency.network.outputs.vpc_id
ingress_cidrs = local.env_vars.locals.web_cidrs
}
Step 10. Plan and apply dev. Format and validate the HCL first. Then run the whole environment with the run-all form of the command. Recent Terragrunt releases spell it run --all, and the older run-all spelling is deprecated, so use the new one.
cd live/dev
terragrunt hcl fmt
terragrunt run --all --non-interactive plan
Terragrunt discovers three units, builds the graph and plans them. Expect network and artifacts to plan first, with web-sg waiting on network. Because the VPC does not exist yet, the web-sg plan uses the mock VPC ID. Output formatting varies by release, but the shape looks like this.
INFO Discovered 3 units
INFO Units that will be run, in order:
INFO Group 1
INFO - live/dev/us-east-1/artifacts
INFO - live/dev/us-east-1/network
INFO Group 2
INFO - live/dev/us-east-1/web-sg
...
Plan: 7 to add, 0 to change, 0 to destroy. (network)
Plan: 4 to add, 0 to change, 0 to destroy. (artifacts)
Plan: 3 to add, 0 to change, 0 to destroy. (web-sg)
Read the plan. The counts should match the modules: the VPC, gateway, two subnets, route table and two associations make seven for networking, the bucket plus three settings make four, and the group plus two rules make three. Your exact numbers depend on how Terragrunt groups its output, so look for the resource names rather than the totals. When they look right, apply.
terragrunt run --all --non-interactive apply
terragrunt run --all --non-interactive output
Apply takes a minute or two. Terragrunt applies network before web-sg, then the real VPC ID replaces the mock. Verify the state landed where it should.
aws s3 ls "s3://tg-lab-state-${ACCOUNT_ID}/live/dev/us-east-1/" --recursive
You should see three keys ending in tofu.tfstate, one per unit, such as live/dev/us-east-1/network/tofu.tfstate. Together with a quick look at the VPC in the console, that confirms the first environment. Commit now with git add -A && git commit -m "dev environment".
Steps 11-13: Promote to Staging and Prod, Add CI, Tear Down
Step 11. Promote to staging and prod by copying folders. This is the payoff. The unit files contain no environment-specific values, so you copy dev and change one file per environment.
cd ~/tg-aws-lab/live
for env in staging prod; do
cp -r dev/us-east-1 $env/
find $env -name .terragrunt-cache -prune -exec rm -rf {} +
done
cat > staging/env.hcl <<'EOF'
locals {
env = "staging"
vpc_cidr = "10.20.0.0/16"
web_cidrs = ["10.0.0.0/8"]
}
EOF
cat > prod/env.hcl <<'EOF'
locals {
env = "prod"
vpc_cidr = "10.30.0.0/16"
web_cidrs = ["10.0.0.0/8"]
}
EOF
The copies carry their own region.hcl, so nothing else changes. Add one guard to production. A prevent_destroy attribute in the bucket unit makes Terragrunt refuse a destroy there until someone edits the file on purpose.
# live/prod/us-east-1/artifacts/terragrunt.hcl
include "root" {
path = find_in_parent_folders("root.hcl")
}
include "envcommon" {
path = "${dirname(find_in_parent_folders("root.hcl"))}/_envcommon/artifacts.hcl"
}
prevent_destroy = true
Apply staging, read its plan, then apply prod the same way. Run each from its own folder, and run prod last, with a human reading the plan. Selection flags for running a subset of units have been renamed across releases, so check terragrunt run --help on your version when you need them.
cd ~/tg-aws-lab/live/staging
terragrunt run --all --non-interactive plan
terragrunt run --all --non-interactive apply
cd ../prod
terragrunt run --all --non-interactive plan
# review the plan, then:
terragrunt run --all --non-interactive apply
Step 12. Add a CI plan on every pull request. A plan job per environment gives reviewers the diff before merge. The workflow below uses GitHub OIDC so no AWS keys sit in secrets. Create a read-only IAM role for planning, trust the repo’s OIDC subject, and store its ARN as a repository variable. Check for the newest major version of each action before you copy the pins.
# .github/workflows/plan.yml
name: plan
on:
pull_request:
paths:
- "live/**"
- "modules/**"
- "_envcommon/**"
- "root.hcl"
- ".mise.toml"
permissions:
id-token: write
contents: read
jobs:
plan:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
env: [dev, staging, prod]
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_PLAN_ROLE_ARN }}
aws-region: us-east-1
- name: Plan ${{ matrix.env }}
working-directory: live/${{ matrix.env }}
run: terragrunt run --all --non-interactive plan
The mise action reads .mise.toml, so CI installs the same OpenTofu and Terragrunt versions you pinned in Step 2. Keep apply manual or behind an environment approval, and give it a separate, narrower trust policy than the plan role. If you later add serverless units, the Lambda and SQS Terraform tutorial shows a module you can drop in beside these three.
Step 13. Tear everything down. Destroy in reverse dependency order, which Terragrunt handles for you. Remove the prod guard first, because it blocks the destroy by design.
cd ~/tg-aws-lab/live/prod/us-east-1/artifacts
sed -i '/prevent_destroy/d' terragrunt.hcl
cd ~/tg-aws-lab/live
for env in prod staging dev; do
(cd $env && terragrunt run --all --non-interactive destroy)
done
Versioned buckets do not delete while old object versions exist. The artifact buckets are empty here, so the destroy works. The state bucket is outside Terragrunt’s control by design. Empty it, including versions, and delete it from the console or CLI once you are done. Then run git status and confirm no backend.tf or cache folder is staged.
Common Pitfalls in a Terragrunt Setup
Most Terragrunt pain comes from a handful of repeat mistakes. Each of these has cost real teams an afternoon, and each is cheap to avoid once you know it.
- Naming the root file terragrunt.hcl. Terragrunt then treats the root as a unit, tries to run it, and complains about missing sources. Use
root.hcland include it by name. The fix takes ten seconds, but finding the cause takes an hour if you do not know to look. - Committing generated files. The
backend.tf,provider.tfand.terragrunt-cachefolders change on every run and bloat diffs. Ignore them. Reviewers should only see hand-written HCL. - Letting mock outputs reach apply. If you forget
mock_outputs_allowed_terraform_commands, a fake VPC ID can flow into a real resource. Restrict mocks to init, validate and plan every single time. - Running apply across prod without reading the plan.
run --allis powerful because it touches many units at once, and that is exactly why it is dangerous. Plan first, read it, then apply. Gate prod behind a manual approval in CI. - Mixing Terraform and OpenTofu on the same state. A state file written by a newer engine can refuse to open in an older one. Pin
TG_TF_PATHand the tool versions in.mise.tomlso nobody switches engines by accident. - Hardcoding account IDs and bucket names. Copy-pasting dev values into prod produces cross-account surprises. Derive them with
get_aws_account_id()and keepallowed_account_idsin the generated provider. - Nesting includes too deep. A root, one shared include and a unit file is plenty. Three layers of includes make it impossible to tell where a value comes from. If you need
terragrunt renderto debug a unit, the tree is already too clever. - Ignoring existing resources. Teams that adopt Terragrunt on a live account usually have hand-built resources. Bring them under management with import blocks for existing AWS resources before you add them to a unit, or the first apply tries to create duplicates.
Troubleshooting: 12 Errors and Their Fixes
When a run fails, read the first error, not the last. Terragrunt wraps OpenTofu’s messages, so the useful line is often near the top. Use this table as a lookup, and check terragrunt --version and tofu version first, because several fixes depend on release age.
| Symptom | Likely cause | Fix |
|---|---|---|
Could not find a root.hcl or find_in_parent_folders error |
Running from the wrong folder, or the file is named differently | Run inside live/ and confirm root.hcl sits at the repo root |
terraform: command not found |
TG_TF_PATH not set, so Terragrunt looks for Terraform |
Run mise trust, reopen the shell, check echo $TG_TF_PATH |
| S3 bucket does not exist during init | Step 6 skipped, or the profile points at another account | Re-run the bootstrap commands and compare aws sts get-caller-identity |
| Backend configuration changed, reinitialization required | Backend block edited after the first init | Run terragrunt init -reconfigure in the affected unit |
Unsupported argument use_lockfile |
Engine older than the lockfile feature | Upgrade to the pinned OpenTofu 1.13.x line |
dependency.network.outputs is an object with no attributes |
Dependency not applied yet and no mock outputs set | Apply network first, or add mock_outputs for plan and validate |
| Error acquiring the state lock | A crashed run left a lock file behind | Confirm nobody is running, then terragrunt force-unlock LOCK_ID |
ExpiredToken or SSO session expired |
Short-lived credentials timed out mid-run | Run aws sso login --profile tg-lab and retry |
| BucketAlreadyExists on the state bucket | Bucket names are global and someone owns yours | Keep the account ID in the name, or add your org prefix |
Unknown flag --terragrunt-non-interactive |
Old flag spelling from an older guide | Use --non-interactive or TG_NON_INTERACTIVE=true |
| No valid credential sources in CI | Workflow lacks id-token: write or the role trust is wrong |
Add the permission, then check the OIDC subject in the role trust policy |
Stale or huge .terragrunt-cache causes odd plans |
Cached module copies out of date | Delete the folders with find . -name .terragrunt-cache -prune -exec rm -rf {} + |
Two debugging habits save the most time. First, run a single unit from its own folder with plain terragrunt plan to take the graph out of the picture. Second, turn up logging with --log-level debug when a value looks wrong, and read which file supplied it. Terragrunt is deterministic. If a value is surprising, one of your HCL files put it there.
Advanced Tips for Larger Estates
The lab uses one account for clarity. Real estates split accounts by environment, and the layout already supports it. Add an account.hcl beside each env.hcl, read it in root.hcl, and assume a role per account in the generated provider. Because allowed_account_ids is already in place, a mistaken profile fails fast instead of deploying into the wrong account.
Speed up large run-all jobs
Every unit downloads the AWS provider by default, and that adds up across dozens of units. Point OpenTofu at a shared plugin cache with the TF_PLUGIN_CACHE_DIR environment variable, and look at Terragrunt’s provider cache server option in the docs for your version. Also keep modules small. A unit with 200 resources plans slowly no matter what wraps it.
Add units without touching the root
New components follow a three-step recipe: write the module, add an _envcommon file, then add a unit folder per environment. A load balancer firewall is a good next candidate, and our guide to WAF in front of an ALB has a module you can adapt. The same pattern works outside AWS, as in the Terraform on Google Cloud tutorial, because the root file only generates a different provider block.
Know the newer orchestration options
Terragrunt keeps adding higher-level constructs, including a stacks feature that generates groups of units from a single file. HashiCorp has its own Stacks concept too, and the Terraform Enterprise 2.0 line added support for multi-module, cross-environment, cross-region and multi-account orchestration. A November 2026 write-up on Terragrunt, OpenTofu and Terraform Stacks compares the monorepo and state-management trade-offs if you are choosing between them. Start with the plain unit layout in this guide, and adopt stacks only when copying folders becomes the bottleneck.
Three more habits pay off at scale:
- Drift detection on a schedule. Run
terragrunt run --all plan -detailed-exitcodenightly in CI and alert when the exit code is 2. Drift found on Tuesday is cheaper than drift found during an outage. - Separate roles for plan and apply. Give plan a read-only role that any pull request can assume, and keep apply behind an approval environment with write access.
- Policy checks before apply. Run a policy scanner such as Checkov or Trivy against rendered plans so an open security group never reaches prod.
Cost, Security and State Hygiene
The lab costs close to nothing. S3 has no minimum charge, the network objects are free while idle, and the state files are a few kilobytes each. The expensive mistakes come later, when someone copies the network module into a design with NAT gateways and leaves it running. Keep the budget alert from the prerequisites switched on, and tag everything. The generated provider already stamps Environment, ManagedBy and Project on every resource, so cost reports split cleanly by environment.
State deserves the same care as a database. It can hold secrets in plain text, so treat read access to the state bucket as production access. Keep versioning on, keep the public access block on, and restrict who can write to the bucket. In multi-account setups, store state in a dedicated account that only the pipeline role can reach. Never paste a state file into a ticket or a chat.
Use these quick checks before you call the setup done:
- Run
aws s3api get-bucket-versioningon the state bucket and confirmEnabled. - Confirm no IAM user keys exist for the pipeline, only the OIDC role.
- Grep the repo for account IDs and ARNs. Anything you find should come from a function or a variable.
- Check that
git ls-fileslists nobackend.tf,provider.tfor cache folders.
Terragrunt vs Workspaces vs a Hosted Platform
Terragrunt is not the only way to manage several environments, and it is not always the right one. The table compares the three common approaches on the points that decide the choice in practice.
| Approach | State isolation | Repeated config | Hosting | Best fit |
|---|---|---|---|---|
| Terragrunt with OpenTofu | One state file per unit | Generated from root and shared includes | Your own S3 bucket and CI | Teams with several environments and accounts who want files in Git |
| OpenTofu workspaces | One state per workspace, one shared backend | Same code, variable files per workspace | Your own bucket | Small projects with near-identical environments |
| Hosted platform such as HCP Terraform | Managed per workspace | Workspaces and variable sets | Vendor SaaS | Teams that want a managed UI, policy and run history |
| Plain folders, copy and paste | One state per folder | Copied by hand | Your own bucket | Throwaway prototypes only |
On hosted pricing, check current terms before you decide. One analysis reports that HCP Terraform’s free plans are limited to 500 managed resources, and you can see that and other license trade-offs in this 2026 Terraform vs OpenTofu write-up. Plenty of teams stay on a self-managed bucket plus Terragrunt precisely because it removes per-resource billing from the equation. Others pay for the hosted UI and policy tooling and skip the wrapper. Both choices are defensible. Pick the one that matches the size of your platform team.
A simple rule works for most readers. If you have one environment, use plain OpenTofu. If you have two or three nearly identical ones, workspaces may do. Once you have separate accounts, regions or different sizes per environment, a Terragrunt setup starts to pay for itself, because copying a folder beats re-describing a backend.
The Complete Working Project
Here is the final state of the repository after Step 11. Every file in the list is one you wrote above, and nothing else is needed. If you want a broader view of related infrastructure guides, our cloud computing coverage groups them by provider.
tg-aws-lab/
├── .mise.toml (Step 2)
├── .gitignore (Step 5)
├── .github/workflows/plan.yml (Step 12)
├── root.hcl (Step 7)
├── _envcommon/{network,web-sg,artifacts}.hcl (Step 9)
├── modules/{network,web-sg,artifacts}/{main.tf,versions.tf} (Step 8)
└── live/{dev,staging,prod}/
├── env.hcl (Steps 9 and 11)
└── us-east-1/
├── region.hcl
└── {network,web-sg,artifacts}/terragrunt.hcl
Finish with a verification script. It checks the tools, the account, the state keys and the generated files in one pass, so you can run it after any change.
#!/usr/bin/env bash
set -euo pipefail
echo "== tools"
tofu version | head -1
terragrunt --version
echo "== account"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo "$ACCOUNT_ID"
echo "== state keys"
aws s3 ls "s3://tg-lab-state-${ACCOUNT_ID}/live/" --recursive | grep -c 'tofu.tfstate'
echo "== plan is clean"
for env in dev staging prod; do
(cd live/$env && terragrunt run --all --non-interactive plan -detailed-exitcode)
&& echo "$env: no changes" || echo "$env: changes or error, review"
done
With all three environments applied, the script should report nine state keys and a clean plan in each environment. A clean plan after apply is the real test. It proves the code and the state agree, and that nothing in your generated files drifts between runs.
Frequently Asked Questions
Does Terragrunt work with OpenTofu or only Terraform? It works with both. Terragrunt calls whatever binary you point it at, and TG_TF_PATH=tofu selects OpenTofu. The HCL you write stays identical.
Which OpenTofu version should I use for a new project in November 2026? Use the 1.13 line. OpenTofu v1.13.0 was released on September 29, 2026, and the project says the series gets security support through August 2027. Pin it as 1.13.x and verify with tofu version.
Do I still need a DynamoDB table for state locking? Not on current OpenTofu releases. Native S3 lock files, enabled with use_lockfile = true, handle locking inside the bucket. Older tutorials that create a table are written for earlier engines.
Why is the root file called root.hcl? Terragrunt treats every terragrunt.hcl as a runnable unit. A root file with that name can be picked up by run-all commands and fail. The root.hcl name keeps it out of the unit list.
Can I run a single unit instead of the whole environment? Yes. Change into the unit’s folder and run plain terragrunt plan or terragrunt apply. Terragrunt then reads that one unit and its dependencies’ outputs, and it does not touch siblings.
How do I stop a production resource from being destroyed by accident? Set prevent_destroy = true in that unit’s terragrunt.hcl, as in Step 11. Pair it with an approval gate in CI and a restricted apply role so a destroy needs a deliberate edit and a human sign-off.
What is the difference between a unit and a module? A module is reusable OpenTofu code. A unit is a folder with a terragrunt.hcl that points at a module, supplies inputs and owns one state file. Many units can use one module.
Is Terragrunt free? Terragrunt is open source from Gruntwork and installs without a license fee. Your costs come from the AWS resources you deploy and from any CI minutes or hosted tools you add on top.