terraform-best-practices
Terraform infrastructure-as-code best practices for scalable and maintainable cloud infrastructure. Use when writing Terraform modules, managing infrastructure state, or implementing infrastructure automation at scale.
Best use case
terraform-best-practices is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Terraform infrastructure-as-code best practices for scalable and maintainable cloud infrastructure. Use when writing Terraform modules, managing infrastructure state, or implementing infrastructure automation at scale.
Teams using terraform-best-practices should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/terraform-best-practices/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How terraform-best-practices Compares
| Feature / Agent | terraform-best-practices | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Terraform infrastructure-as-code best practices for scalable and maintainable cloud infrastructure. Use when writing Terraform modules, managing infrastructure state, or implementing infrastructure automation at scale.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Terraform Best Practices
Expert guidance for building production-grade Terraform infrastructure with enterprise patterns for module design, state management, security, testing, and multi-environment deployments.
## When to Use This Skill
- Writing reusable Terraform modules for teams or organizations
- Setting up secure remote state management and backend configuration
- Designing multi-environment infrastructure (dev/staging/prod)
- Implementing infrastructure CI/CD pipelines with automated validation
- Managing infrastructure at scale across multiple teams or projects
- Migrating from manual infrastructure to infrastructure-as-code
- Refactoring existing Terraform for better maintainability
- Implementing security best practices for infrastructure code
## Core Concepts
### Module Design Philosophy
- **Composition over monoliths**: Break infrastructure into reusable child modules
- **Standard structure**: main.tf, variables.tf, outputs.tf, versions.tf, README.md
- **Type constraints**: Use validation blocks and complex types for safety
- **Dynamic blocks**: Enable flexible configuration without duplication
### State Management Principles
- **Remote backends**: S3+DynamoDB or Terraform Cloud for team collaboration
- **State encryption**: KMS encryption at rest and in transit (mandatory)
- **State locking**: Prevent concurrent modifications with DynamoDB
- **Workspace strategy**: Directory-based for production, workspaces for similar envs
### Security Fundamentals
- **Secret management**: AWS Secrets Manager, HashiCorp Vault (never hardcode)
- **Least privilege**: Separate IAM roles per environment
- **Security scanning**: tfsec, Checkov, Terrascan in CI/CD
- **Resource tagging**: Enable cost tracking, ownership, compliance
### Testing & Validation
- **Pre-commit hooks**: Format, validate, lint before commits
- **Plan review**: Always save and review plans before apply
- **Automated testing**: Terratest for critical infrastructure modules
- **Policy as code**: OPA/Sentinel for compliance enforcement
## Quick Reference
| Task | Load reference |
| --- | --- |
| Module structure, variables, outputs, dynamic blocks | `skills/terraform-best-practices/references/module-design.md` |
| Remote backends, state encryption, workspace strategies | `skills/terraform-best-practices/references/state-management.md` |
| Variable precedence, tfvars, Terragrunt DRY config | `skills/terraform-best-practices/references/environment-management.md` |
| Secrets, IAM, scanning tools, resource tagging | `skills/terraform-best-practices/references/security.md` |
| Pre-commit hooks, Terratest, policy as code | `skills/terraform-best-practices/references/testing-validation.md` |
| Comprehensive checklist for all areas | `skills/terraform-best-practices/references/best-practices-summary.md` |
## Workflow
### 1. Project Setup
```bash
# Initialize directory structure
mkdir -p {modules,environments/{dev,staging,prod}}
# Set up remote backend (bootstrap S3 + DynamoDB first)
# Configure backend.tf with encryption and locking
```
### 2. Module Development
```bash
# Create module with standard structure
cd modules/my-module
touch main.tf variables.tf outputs.tf versions.tf README.md
# Add validation to variables
# Use complex types for structured inputs
# Document outputs with descriptions
```
### 3. Security Hardening
```bash
# Mark sensitive variables
# Use secret management for credentials
# Configure state encryption
# Set up security scanning in CI/CD
```
### 4. Testing Pipeline
```bash
# Install pre-commit hooks
pre-commit install
# Run validation locally
terraform init
terraform validate
terraform fmt -check
# Security scanning
tfsec .
checkov -d .
# Automated tests (critical modules)
cd tests && go test -v
```
### 5. Deployment Process
```bash
# Plan with output file
terraform plan -out=tfplan
# Review plan thoroughly
terraform show tfplan
# Apply only after approval
terraform apply tfplan
# Verify deployment
terraform output
```
### 6. Multi-Environment Management
```bash
# Use directory-based isolation for production
cd environments/prod
terraform init
terraform workspace list
# Or use Terragrunt for DRY backend config
terragrunt plan
```
## Common Mistakes
❌ **Hardcoding secrets in code** → Use secret management services
❌ **No state locking** → Enable DynamoDB locking to prevent conflicts
❌ **Skipping plan review** → Always save and review execution plans
❌ **No version constraints** → Pin provider and module versions
❌ **Local state in teams** → Use remote backends for collaboration
❌ **No security scanning** → Integrate tfsec/Checkov in CI/CD
❌ **Missing resource tags** → Tag all resources for cost/ownership tracking
❌ **No automated testing** → Write Terratest for critical modules
❌ **Monolithic modules** → Break into composable child modules
❌ **No backup strategy** → Enable S3 versioning on state buckets
## Resources
- **Official Docs**: https://developer.hashicorp.com/terraform/docs
- **Style Guide**: https://developer.hashicorp.com/terraform/language/syntax/style
- **Module Registry**: https://registry.terraform.io/
- **Terragrunt**: https://terragrunt.gruntwork.io/
- **Terratest**: https://terratest.gruntwork.io/
- **tfsec**: https://aquasecurity.github.io/tfsec/
- **Checkov**: https://www.checkov.io/
- **Best Practices**: https://www.terraform-best-practices.com/
- **AWS Provider**: https://registry.terraform.io/providers/hashicorp/aws/latest/docsRelated Skills
secure-coding-practices
Secure coding practices and defensive programming patterns for building security-first applications. Use when implementing authentication, handling user input, managing sensitive data, or conducting secure code reviews.
writing-skills
Use when creating new skills, editing existing skills, or verifying skills work before deployment - applies TDD to process documentation by testing with subagents before writing, iterating until bulletproof against rationalization
workflow-security-audit
Comprehensive security assessment and remediation. Use for security reviews, compliance checks, vulnerability assessments.
workflow-performance
Systematic performance analysis and optimization. Use when things are slow, need optimization, or preparing for scale.
workflow-feature
Complete feature development workflow from design to deployment. Use when implementing new features or functionality.
workflow-feature-development
Complete workflow for developing new features from design to deployment. Use when starting a new feature, adding functionality, or building something new.
workflow-bug-fix
Systematic approach to identifying, fixing, and validating bug fixes. Use when fixing bugs, resolving issues, or addressing errors.
wiring-audit
User-triggered audit that finds wiring drift between a project's UI surfaces and backend capabilities — orphan surfaces (UI calls endpoints/hooks/procedures that no longer exist), unwired capabilities (backend routes/exports that nothing surfaces), shape drift (both exist but contracts mismatch), method drift (URL matches, HTTP verb does not), validation drift (frontend vs backend rules diverged), permission drift (UI exposes what backend forbids or vice versa), stale labels (UI text references renamed backend concepts), and unsurfaced configuration (env vars or flags that gate behavior with no UI or CLI to control them). This skill should be used when the user asks to "audit our wiring," "find UI/backend drift," "find unwired capabilities," "find stale surfaces," "check for contract violations," "find unused endpoints," "find unused hooks," "what mismatches between UI and backend," or any similar request whose deliverable is a prioritized findings report rather than a descriptive snapshot. Generic across UI frameworks but optimized for React applications (hooks, fetch, react-query, SWR, tRPC, server actions, react-router, Next.js). Not for descriptive architectural snapshots (use architectural-analysis), security audits (use security-auditor), or performance audits (use workflow-performance).
webapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Use when verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
web-researcher
Use this skill when you need to research a topic online, gather information from multiple sources, or evaluate source credibility. Trigger phrases: 'research', 'find information about', 'look up', 'investigate'. Not for academic systematic reviews (use literature-reviewer) or fact-checking specific claims (use fact-checker).
visual-modes
Use when activating visual showcase modes (supersaiyan, kamehameha, over9000) for UI or interaction design - provides mode-specific enhancement checklists.
vibe-security
Comprehensive secure coding guide covering OWASP web vulnerabilities with prevention patterns and checklists. Use when writing or reviewing web application code to prevent XSS, CSRF, SSRF, SQL injection, access control flaws, and other common security vulnerabilities.