Terragrunt for Beginners
Managing Remote State with Terragrunt
Configuring Remote State With Terragrunt Using AWS S3
In this guide, you’ll learn how to store your Terraform state file in Amazon S3 and leverage Terragrunt to automate and simplify remote state management. By adopting a consistent backend pattern, you remove repetitive setup steps and let your team focus on provisioning infrastructure.
Terraform remote state in S3 provides durability and versioning, while Terragrunt adds dynamic environment management—enabling seamless transitions between development, staging, and production.
Why Use AWS S3 for Terraform Remote State?
- Durable and highly available storage with versioning
- Built-in encryption and access control via IAM policies
- Integration with DynamoDB for state locking to prevent race conditions
Terragrunt Approaches to Remote State
Terragrunt supports two strategies for configuring your S3 backend. Choose the one that aligns with your workflow and organizational standards:
Approach | Configuration Location | Pros | Cons |
---|---|---|---|
Generate Block | .tf files via generate | Highly customizable<br>DRY Terraform modules | Additional generated files |
Remote State | terragrunt.hcl via remote_state | Minimal module code<br>Single source of truth | Less direct control over backend |
1. Generate Block
With the generate
block, Terragrunt produces a Terraform file in each module directory. Define your S3 backend settings once, and Terragrunt will insert a backend "s3"
block into every generated .tf
file.
Example terragrunt.hcl
snippet:
generate "backend" {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
contents = <<EOF
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "env/${local.environment}/terraform.tfstate"
region = "us-west-2"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
EOF
}
2. Remote State Block
Alternatively, the remote_state
block in terragrunt.hcl
encapsulates both the backend configuration and state locking. This method reduces Terraform code in your modules and centralizes state settings.
Example terragrunt.hcl
snippet:
remote_state {
backend = "s3"
config = {
bucket = "my-terraform-state"
key = "env/${local.environment}/terraform.tfstate"
region = "us-west-2"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
Warning
You cannot combine both generate
and remote_state
approaches within the same project. Pick one strategy to avoid configuration conflicts.
Additional Resources
- Terraform Backend Configuration
- Terragrunt Documentation
- AWS S3 User Guide
- DynamoDB Locking for Terraform
Watch Video
Watch video content