name: Terraform Best Practices
description: Comprehensive rules for Terraform and Terragrunt development
Terraform & Terragrunt Development Standards
Code Structure & Organization
- Always use consistent resource naming:
{environment}-{service}-{resource_type}
- Group related resources in the same .tf file (e.g., all networking in network.tf)
- Use meaningful file names: variables.tf, outputs.tf, main.tf, locals.tf
- For Terragrunt: keep terragrunt.hcl files focused and minimal
Resource Configuration
- Always include required_providers block with explicit version constraints
- Use data sources instead of hardcoded values for external resources
- Include comprehensive tags for all AWS resources (at minimum: Name, Environment, Project, Owner)
- Use locals block for computed or repeated values
- Prefer resource-specific data sources over generic ones
Variables & Outputs
- Always include description and type for variables
- Use validation blocks for variables when constraints are known
- Mark sensitive variables as sensitive = true
- Include meaningful descriptions for all outputs
- Group related variables logically
Security & Best Practices
- Never hardcode secrets, API keys, or passwords
- Use random_password or similar for generated secrets
- Implement least-privilege IAM policies
- Always encrypt storage at rest and in transit
- Use security groups with specific ports and sources, avoid 0.0.0.0/0 when possible
Terragrunt Specific
- Use dependency blocks to manage resource dependencies
- Leverage remote_state for cross-stack references
- Use generate blocks for common provider configurations
- Keep inputs block organized and documented
- Use include blocks for shared configurations
State Management
- Always use remote state backends (S3 + DynamoDB for AWS)
- Use unique state file names per environment/stack
- Include state locking configuration
- Never commit .tfstate files to version control
Documentation
- Include README.md with usage examples
- Document all module inputs and outputs
- Provide examples of typical usage patterns
- Include terraform-docs formatted comments