Terragrunt for Beginners
Terragrunt Configuration
Directory Structure
A well-organized directory layout simplifies management of Terraform configurations with Terragrunt, promotes reuse, and makes environment-specific customizations straightforward.
Key Components
Component | Purpose | Location |
---|---|---|
Root terragrunt.hcl | Defines global settings (remote state, providers, hooks) | /terragrunt.hcl |
Modules | Reusable Terraform logic (resources, variables) | /modules/<module-name>/ |
Environments | Environment-specific configurations | /envs/<environment>/ |
Shared Variables | Centralizes common variable values per environment | /envs/<environment>/common-vars.hcl |
Example Directory Tree
.
├── terragrunt.hcl # Global Terragrunt configuration
├── modules # Reusable Terraform modules
│ ├── app
│ │ ├── main.tf
│ │ └── variables.tf
│ └── mysql
│ ├── main.tf
│ └── variables.tf
└── envs # Environment-specific configurations
├── dev
│ ├── account.hcl # Dev account ID, region, etc.
│ ├── common-vars.hcl # Shared dev variables
│ ├── app
│ │ └── terragrunt.hcl # Inherits root, adds app settings
│ └── mysql
│ └── terragrunt.hcl # Inherits root, adds MySQL settings
└── prod
├── account.hcl # Prod account ID, region, etc.
├── common-vars.hcl # Shared prod variables
├── app
│ └── terragrunt.hcl
└── mysql
└── terragrunt.hcl
How It Works
Global Settings
The rootterragrunt.hcl
provides defaults for all modules and environments:- Remote state backend configuration
- Shared providers
- Pre/post hooks for automation
Note
Define secure and centralized remote state backends in your root file to maintain state consistency across teams.
Environment Overrides
Each environment directory (envs/dev
,envs/prod
) contains:account.hcl
for environment-specific parameters (account IDs, AWS region, etc.)common-vars.hcl
to share variable values among all components
Component-Specific Configuration
Insideenvs/<environment>/<component>/terragrunt.hcl
you:- Include both the root configuration and the environment’s
account.hcl
- Reference the corresponding module from
modules/<component>
- Override or supplement module inputs as needed
- Include both the root configuration and the environment’s
Shared Variables
Usecommon-vars.hcl
to avoid repetition:inputs = { project_name = "example" tags = { owner = "team-infra" } }
Warning
Avoid duplicating variables across component configs. Centralize values in
common-vars.hcl
to prevent drift.
Benefits
- Modularity: Break infrastructure into reusable modules.
- Clarity: Isolate environment-specific settings from shared defaults.
- Scalability: Easily add new environments or components without refactoring existing code.
Links and References
Watch Video
Watch video content