Setting Up Remote State Backend with S3
🔁 Setting Up Remote State Backend with generate Blocks
Terragrunt makes it easy to define remote state backends (like S3) in a DRY and reusable way using generate blocks.
The generate block dynamically creates Terraform files (e.g. backend.tf) before terraform init runs, so you don’t have to write the same backend config in every module.
📁 Directory Structure
live/
├── terragrunt.hcl # Root-level config with backend
└── dev/
└── s3/
└── terragrunt.hcl # Module-specific config
🌍 Root-level live/terragrunt.hcl
remote_state {
backend = "s3"
config = {
bucket = "my-terraform-state-bucket"
key = "${path_relative_to_include()}/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
generate "backend" {
path = "backend.tf"
if_exists = "overwrite"
contents = <<EOF
terraform {
backend "s3" {}
}
EOF
}
This will auto-generate a backend.tf file and enable the S3 backend dynamically.
🌱 Module-Level live/dev/s3/terragrunt.hcl
include {
path = find_in_parent_folders()
}
terraform {
source = "../../../terraform-modules/s3"
}
inputs = {
bucket_name = "my-dev-s3-bucket"
region = "us-east-1"
}
🚀 Running Terragrunt
Navigate to your module directory and run:
terragrunt init
terragrunt apply
Terragrunt will:
- Generate the
backend.tffile - Configure your S3 backend automatically
- Apply the Terraform module with remote state support
✅ Advantages
- Centralized and reusable backend configuration
- No need to repeat backend blocks in every module
- Simple to manage multiple environments
💡 Tip: You can add environment-specific overrides or additional logic usinglocals,inputs, ordependencyblocks inside Terragrunt files.
No comments