Terraform Style Guide
Generate and maintain Terraform code following HashiCorp's official style conventions and best practices.
Reference: HashiCorp Terraform Style Guide
Code Generation Strategy
When generating Terraform code:
- Start with provider configuration and version constraints
- Create data sources before dependent resources
- Build resources in dependency order
- Add outputs for key resource attributes
- Use variables for all configurable values
File Organization
Example Structure
Code Formatting
Indentation and Alignment
- Use two spaces per nesting level (no tabs)
- Align equals signs for consecutive arguments
Block Organization
Arguments precede blocks, with meta-arguments first:
Naming Conventions
- Use lowercase with underscores for all names
- Use descriptive nouns excluding the resource type
- Be specific and meaningful
- Resource names must be singular, not plural
- Default to
mainfor resources where a specific descriptive name is redundant or unavailable, provided only one instance exists
Variables
Every variable must include type and description:
Outputs
Every output must include description:
Dynamic Resource Creation
Prefer for_each over count
count for Conditional Creation
Security Best Practices
Refer to SECURITY.md. It includes guidance on encrypting resources, preventing sensitive data in state, and secure configurations.
Version Pinning
Use the latest major version of each provider and the latest minor version of Terraform, unless otherwise constrained by a dependency lock file or by other modules used by the configuration.
Version constraint operators:
= 1.0.0- Exact version>= 1.0.0- Greater than or equal~> 1.0- Allow rightmost component to increment>= 1.0, < 2.0- Version range
Provider Configuration
Version Control
Never commit:
terraform.tfstate,terraform.tfstate.backup.terraform/directory*.tfplan.tfvarsfiles with sensitive data
Always commit:
- All
.tfconfiguration files .terraform.lock.hcl(dependency lock file)
Validation Tools
Run before committing:
Additional tools:
tflint- Linting and best practicescheckov/tfsec- Security scanning
Code Review Checklist
- Code formatted with
terraform fmt - Configuration validated with
terraform validate - Files organized according to standard structure
- All variables have type and description
- All outputs have descriptions
- Resource names use descriptive nouns with underscores
- Version constraints pinned explicitly
- Sensitive values marked with
sensitive = true - No hardcoded credentials or secrets
- Security best practices applied
Based on: HashiCorp Terraform Style Guide


