1. AWS Provider Configuration
Begin by defining the AWS provider. You can author this directly in Terraform or generate it via Terragrunt. Exampleprovider.tf:
variables.tf:
2. Remote State Management with S3 and DynamoDB
Terragrunt simplifies configuring S3 as a remote backend and DynamoDB for state locking. Exampleterragrunt.hcl:
Enabling
encrypt = true ensures that state files are encrypted at rest. DynamoDB locking prevents concurrent state mutations.3. IAM Role Assumption for Fine-Grained Permissions
Use Terragrunt’sgenerate block to create a provider that assumes an IAM role:
4. Organizing AWS-Specific Variables
Centralize common AWS settings in a sharedvariables.tf:
5. Modular Infrastructure and AWS Best Practices
Adopt a modular layout and separate environments for scalable, maintainable Terraform code.Recommended Layout
| Directory | Purpose | Example Files |
|---|---|---|
| modules/ | Reusable Terraform modules | ec2-instance, rds |
| envs/dev/ | Development environment configuration | terragrunt.hcl |
| envs/staging/ | Staging environment configuration | terragrunt.hcl |
| envs/prod/ | Production environment configuration | terragrunt.hcl |
Key Practices
-
Per-Environment Folders
Each folder underenvs/contains its ownterragrunt.hclpointing to shared modules. -
Shared Modules
Store reusable code inmodules/and orchestrate inputs/backends with Terragrunt. -
AWS Well-Architected Framework
Follow AWS Well-Architected Framework for security, performance, and cost optimization.
Avoid committing sensitive credentials to version control. Use AWS IAM roles, environment variables, or Secrets Manager instead.