Terraform Patterns
Predictable infrastructure. Secure state. Modules that compose. No drift.
Opinionated Terraform workflow that turns sprawling HCL into well-structured, secure, production-grade infrastructure code. Covers module design, state management, provider patterns, security hardening, and CI/CD integration.
Not a Terraform tutorial — a set of concrete decisions about how to write infrastructure code that doesn't break at 3 AM.
Slash Commands
| Command |
What it does |
/terraform-patterns review |
Analyze Terraform code for anti-patterns, security issues, and structure problems |
/terraform-patterns module |
Design or refactor a Terraform module with proper inputs, outputs, and composition |
/terraform-patterns security |
Audit Terraform code for security vulnerabilities, secrets exposure, and IAM misconfigurations |
When This Skill Activates
Recognize these patterns from the user:
- "Review this Terraform code"
- "Design a Terraform module for..."
- "My Terraform state is..."
- "Set up remote state backend"
- "Multi-region Terraform deployment"
- "Terraform security review"
- "Module structure best practices"
- "Terraform CI/CD pipeline"
- Any request involving:
.tf files, HCL, Terraform modules, state management, provider configuration, infrastructure-as-code
If the user has .tf files or wants to provision infrastructure with Terraform → this skill applies.
Workflow
/terraform-patterns review — Terraform Code Review
Analyze current state
- Read all
.tf files in the target directory
- Identify module structure (flat vs nested)
- Count resources, data sources, variables, outputs
- Check naming conventions
Apply review checklist
MODULE STRUCTURE
├── Variables have descriptions and type constraints
├── Outputs expose only what consumers need
├── Resources use consistent naming: {provider}_{type}_{purpose}
├── Locals used for computed values and DRY expressions
└── No hardcoded values — everything parameterized or in locals
STATE & BACKEND
├── Remote backend configured (S3, GCS, Azure Blob, Terraform Cloud)
├── State locking enabled (DynamoDB for S3, native for others)
├── State encryption at rest enabled
├── No secrets stored in state (or state access is restricted)
└── Workspaces or directory isolation for environments
PROVIDERS
├── Version constraints use pessimistic operator: ~> 5.0
├── Required providers block in terraform {} block
├── Provider aliases for multi-region or multi-account
└── No provider configuration in child modules
SECURITY
├── No hardcoded secrets, keys, or passwords
├── IAM follows least-privilege principle
├── Encryption enabled for storage, databases, secrets
├── Security groups are not overly permissive (no 0.0.0.0/0 ingress on sensitive ports)
└── Sensitive variables marked with sensitive = true
Generate report
python3 scripts/tf_module_analyzer.py ./terraform
Run security scan
python3 scripts/tf_security_scanner.py ./terraform
/terraform-patterns module — Module Design
Identify module scope
- Single responsibility: one module = one logical grouping
- Determine inputs (variables), outputs, and resource boundaries
- Decide: flat module (single directory) vs nested (calling child modules)
Apply module design checklist
STRUCTURE
├── main.tf — Primary resources
├── variables.tf — All input variables with descriptions and types
├── outputs.tf — All outputs with descriptions
├── versions.tf — terraform {} block with required_providers
├── locals.tf — Computed values and naming conventions
├── data.tf — Data sources (if any)
└── README.md — Usage examples and variable documentation
VARIABLES
├── Every variable has: description, type, validation (where applicable)
├── Sensitive values marked: sensitive = true
├── Defaults provided for optional settings
├── Use object types for related settings: variable "config" { type = object({...}) }
└── Validate with: validation { condition = ... }
OUTPUTS
├── Output IDs, ARNs, endpoints — things consumers need
├── Include description on every output
├── Mark sensitive outputs: sensitive = true
└── Don't output entire resources — only specific attributes
COMPOSITION
├── Root module calls child modules
├── Child modules never call other child modules
├── Pass values explicitly — no hidden data source lookups in child modules
├── Provider configuration only in root module
└── Use module "name" { source = "./modules/name" }
Generate module scaffold
- Output file structure with boilerplate
- Include variable validation blocks
- Add lifecycle rules where appropriate
/terraform-patterns security — Security Audit
Code-level audit
| Check |
Severity |
Fix |
Hardcoded secrets in .tf files |
Critical |
Use variables with sensitive = true or vault |
IAM policy with * actions |
Critical |
Scope to specific actions and resources |
| Security group with 0.0.0.0/0 on port 22/3389 |
Critical |
Restrict to known CIDR blocks or use SSM/bastion |
| S3 bucket without encryption |
High |
Add server_side_encryption_configuration block |
| S3 bucket with public access |
High |
Add aws_s3_bucket_public_access_block |
| RDS without encryption |
High |
Set storage_encrypted = true |
| RDS publicly accessible |
High |
Set publicly_accessible = false |
| CloudTrail not enabled |
Medium |
Add aws_cloudtrail resource |
Missing prevent_destroy on stateful resources |
Medium |
Add lifecycle { prevent_destroy = true } |
Variables without sensitive = true for secrets |
Medium |
Add sensitive = true to secret variables |
State security audit
| Check |
Severity |
Fix |
| Local state file |
Critical |
Migrate to remote backend with encryption |
| Remote state without encryption |
High |
Enable encryption on backend (SSE-S3, KMS) |
| No state locking |
High |
Enable DynamoDB for S3, native for TF Cloud |
| State accessible to all team members |
Medium |
Restrict via IAM policies or TF Cloud teams |
Generate security report
python3 scripts/tf_security_scanner.py ./terraform
python3 scripts/tf_security_scanner.py ./terraform --output json
Tooling
scripts/tf_module_analyzer.py
CLI utility for analyzing Terraform directory structure and module quality.
Features:
- Resource and data source counting
- Variable and output analysis (missing descriptions, types, validation)
- Naming convention checks
- Module composition detection
- File structure validation
- JSON and text output
Usage:
# Analyze a Terraform directory
python3 scripts/tf_module_analyzer.py ./terraform
# JSON output
python3 scripts/tf_module_analyzer.py ./terraform --output json
# Analyze a specific module
python3 scripts/tf_module_analyzer.py ./modules/vpc
scripts/tf_security_scanner.py
CLI utility for scanning .tf files for common security issues.
Features:
- Hardcoded secret detection (AWS keys, passwords, tokens)
- Overly permissive IAM policy detection
- Open security group detection (0.0.0.0/0 on sensitive ports)
- Missing encryption checks (S3, RDS, EBS)
- Public access detection (S3, RDS, EC2)
- Sensitive variable audit
- JSON and text output
Usage:
# Scan a Terraform directory
python3 scripts/tf_security_scanner.py ./terraform
# JSON output
python3 scripts/tf_security_scanner.py ./terraform --output json
# Strict mode (elevate warnings)
python3 scripts/tf_security_scanner.py ./terraform --strict
Patterns catalog
Module layouts (flat, nested, Terragrunt mono-repo), provider pinning and aliasing, the state-management decision tree, CI/CD plan/apply and drift detection, multi-cloud, OpenTofu migration, Infracost cost gates, terraform import and Terragrunt live in references/patterns-catalog.md. Load the section the task needs.
Proactive Triggers
Flag these without being asked:
- No remote backend configured → Migrate to S3/GCS/Azure Blob with locking and encryption.
- Provider without version constraint → Add
version = "~> X.0" to prevent breaking upgrades.
- Hardcoded secrets in .tf files → Use variables with
sensitive = true, or integrate Vault/SSM.
- IAM policy with
"Action": "*" → Scope to specific actions. No wildcard actions in production.
- Security group open to 0.0.0.0/0 on SSH/RDP → Restrict to bastion CIDR or use SSM Session Manager.
- No state locking → Enable DynamoDB table for S3 backend, or use TF Cloud.
- Resources without tags → Add default_tags in provider block. Tags are mandatory for cost tracking.
- Missing
prevent_destroy on databases/storage → Add lifecycle block to prevent accidental deletion.
Installation
One-liner (any tool)
git clone https://github.com/alirezarezvani/claude-skills.git
cp -r claude-skills/engineering/terraform-patterns ~/.claude/skills/
Multi-tool install
./scripts/convert.sh --skill terraform-patterns --tool codex|gemini|cursor|windsurf|openclaw
OpenClaw
clawhub install terraform-patterns
Related Skills
- senior-devops — Broader DevOps scope (CI/CD, monitoring, containerization). Complementary — use terraform-patterns for IaC-specific work, senior-devops for pipeline and infrastructure operations.
- aws-solution-architect — AWS architecture design. Complementary — terraform-patterns implements the infrastructure, aws-solution-architect designs it.
- senior-security — Application security. Complementary — terraform-patterns covers infrastructure security posture, senior-security covers application-level threats.
- ci-cd-pipeline-builder — Pipeline construction. Complementary — terraform-patterns defines infrastructure, ci-cd-pipeline-builder automates deployment.
More in this skill
Load these only when the task needs them.
- references/module-patterns.md — Terraform Module Design Patterns Reference
- references/state-management.md — Terraform State Management Reference
1---2name: "terraform-patterns"3description: "Use for any Terraform module, state backend, provider setup or IaC security review, before editing .tf files. Analyzes modules with tf_module_analyzer.py and scans for misconfigurations with tf_security_scanner.py."4license: MIT5metadata:6 source: https://skillmd.com/skills/alirezarezvani/terraform-patterns7 version: 1.0.08 author: Alireza Rezvani9 category: engineering10 updated: 2026-03-1511---1213# Terraform Patterns1415> Predictable infrastructure. Secure state. Modules that compose. No drift.1617Opinionated Terraform workflow that turns sprawling HCL into well-structured, secure, production-grade infrastructure code. Covers module design, state management, provider patterns, security hardening, and CI/CD integration.1819Not a Terraform tutorial — a set of concrete decisions about how to write infrastructure code that doesn't break at 3 AM.2021---2223## Slash Commands2425| Command | What it does |26|---------|-------------|27| `/terraform-patterns review` | Analyze Terraform code for anti-patterns, security issues, and structure problems |28| `/terraform-patterns module` | Design or refactor a Terraform module with proper inputs, outputs, and composition |29| `/terraform-patterns security` | Audit Terraform code for security vulnerabilities, secrets exposure, and IAM misconfigurations |3031---3233## When This Skill Activates3435Recognize these patterns from the user:3637- "Review this Terraform code"38- "Design a Terraform module for..."39- "My Terraform state is..."40- "Set up remote state backend"41- "Multi-region Terraform deployment"42- "Terraform security review"43- "Module structure best practices"44- "Terraform CI/CD pipeline"45- Any request involving: `.tf` files, HCL, Terraform modules, state management, provider configuration, infrastructure-as-code4647If the user has `.tf` files or wants to provision infrastructure with Terraform → this skill applies.4849---5051## Workflow5253### `/terraform-patterns review` — Terraform Code Review54551. **Analyze current state**56 - Read all `.tf` files in the target directory57 - Identify module structure (flat vs nested)58 - Count resources, data sources, variables, outputs59 - Check naming conventions60612. **Apply review checklist**6263 ```64 MODULE STRUCTURE65 ├── Variables have descriptions and type constraints66 ├── Outputs expose only what consumers need67 ├── Resources use consistent naming: {provider}_{type}_{purpose}68 ├── Locals used for computed values and DRY expressions69 └── No hardcoded values — everything parameterized or in locals7071 STATE & BACKEND72 ├── Remote backend configured (S3, GCS, Azure Blob, Terraform Cloud)73 ├── State locking enabled (DynamoDB for S3, native for others)74 ├── State encryption at rest enabled75 ├── No secrets stored in state (or state access is restricted)76 └── Workspaces or directory isolation for environments7778 PROVIDERS79 ├── Version constraints use pessimistic operator: ~> 5.080 ├── Required providers block in terraform {} block81 ├── Provider aliases for multi-region or multi-account82 └── No provider configuration in child modules8384 SECURITY85 ├── No hardcoded secrets, keys, or passwords86 ├── IAM follows least-privilege principle87 ├── Encryption enabled for storage, databases, secrets88 ├── Security groups are not overly permissive (no 0.0.0.0/0 ingress on sensitive ports)89 └── Sensitive variables marked with sensitive = true90 ```91923. **Generate report**93 ```bash94 python3 scripts/tf_module_analyzer.py ./terraform95 ```96974. **Run security scan**98 ```bash99 python3 scripts/tf_security_scanner.py ./terraform100 ```101102### `/terraform-patterns module` — Module Design1031041. **Identify module scope**105 - Single responsibility: one module = one logical grouping106 - Determine inputs (variables), outputs, and resource boundaries107 - Decide: flat module (single directory) vs nested (calling child modules)1081092. **Apply module design checklist**110111 ```112 STRUCTURE113 ├── main.tf — Primary resources114 ├── variables.tf — All input variables with descriptions and types115 ├── outputs.tf — All outputs with descriptions116 ├── versions.tf — terraform {} block with required_providers117 ├── locals.tf — Computed values and naming conventions118 ├── data.tf — Data sources (if any)119 └── README.md — Usage examples and variable documentation120121 VARIABLES122 ├── Every variable has: description, type, validation (where applicable)123 ├── Sensitive values marked: sensitive = true124 ├── Defaults provided for optional settings125 ├── Use object types for related settings: variable "config" { type = object({...}) }126 └── Validate with: validation { condition = ... }127128 OUTPUTS129 ├── Output IDs, ARNs, endpoints — things consumers need130 ├── Include description on every output131 ├── Mark sensitive outputs: sensitive = true132 └── Don't output entire resources — only specific attributes133134 COMPOSITION135 ├── Root module calls child modules136 ├── Child modules never call other child modules137 ├── Pass values explicitly — no hidden data source lookups in child modules138 ├── Provider configuration only in root module139 └── Use module "name" { source = "./modules/name" }140 ```1411423. **Generate module scaffold**143 - Output file structure with boilerplate144 - Include variable validation blocks145 - Add lifecycle rules where appropriate146147### `/terraform-patterns security` — Security Audit1481491. **Code-level audit**150151 | Check | Severity | Fix |152 |-------|----------|-----|153 | Hardcoded secrets in `.tf` files | Critical | Use variables with sensitive = true or vault |154 | IAM policy with `*` actions | Critical | Scope to specific actions and resources |155 | Security group with 0.0.0.0/0 on port 22/3389 | Critical | Restrict to known CIDR blocks or use SSM/bastion |156 | S3 bucket without encryption | High | Add `server_side_encryption_configuration` block |157 | S3 bucket with public access | High | Add `aws_s3_bucket_public_access_block` |158 | RDS without encryption | High | Set `storage_encrypted = true` |159 | RDS publicly accessible | High | Set `publicly_accessible = false` |160 | CloudTrail not enabled | Medium | Add `aws_cloudtrail` resource |161 | Missing `prevent_destroy` on stateful resources | Medium | Add `lifecycle { prevent_destroy = true }` |162 | Variables without `sensitive = true` for secrets | Medium | Add `sensitive = true` to secret variables |1631642. **State security audit**165166 | Check | Severity | Fix |167 |-------|----------|-----|168 | Local state file | Critical | Migrate to remote backend with encryption |169 | Remote state without encryption | High | Enable encryption on backend (SSE-S3, KMS) |170 | No state locking | High | Enable DynamoDB for S3, native for TF Cloud |171 | State accessible to all team members | Medium | Restrict via IAM policies or TF Cloud teams |1721733. **Generate security report**174 ```bash175 python3 scripts/tf_security_scanner.py ./terraform176 python3 scripts/tf_security_scanner.py ./terraform --output json177 ```178179---180181## Tooling182183### `scripts/tf_module_analyzer.py`184185CLI utility for analyzing Terraform directory structure and module quality.186187**Features:**188- Resource and data source counting189- Variable and output analysis (missing descriptions, types, validation)190- Naming convention checks191- Module composition detection192- File structure validation193- JSON and text output194195**Usage:**196```bash197# Analyze a Terraform directory198python3 scripts/tf_module_analyzer.py ./terraform199200# JSON output201python3 scripts/tf_module_analyzer.py ./terraform --output json202203# Analyze a specific module204python3 scripts/tf_module_analyzer.py ./modules/vpc205```206207### `scripts/tf_security_scanner.py`208209CLI utility for scanning `.tf` files for common security issues.210211**Features:**212- Hardcoded secret detection (AWS keys, passwords, tokens)213- Overly permissive IAM policy detection214- Open security group detection (0.0.0.0/0 on sensitive ports)215- Missing encryption checks (S3, RDS, EBS)216- Public access detection (S3, RDS, EC2)217- Sensitive variable audit218- JSON and text output219220**Usage:**221```bash222# Scan a Terraform directory223python3 scripts/tf_security_scanner.py ./terraform224225# JSON output226python3 scripts/tf_security_scanner.py ./terraform --output json227228# Strict mode (elevate warnings)229python3 scripts/tf_security_scanner.py ./terraform --strict230```231232---233234## Patterns catalog235236Module layouts (flat, nested, Terragrunt mono-repo), provider pinning and aliasing, the state-management decision tree, CI/CD plan/apply and drift detection, multi-cloud, OpenTofu migration, Infracost cost gates, `terraform import` and Terragrunt live in [references/patterns-catalog.md](references/patterns-catalog.md). Load the section the task needs.237238---239240## Proactive Triggers241242Flag these without being asked:243244- **No remote backend configured** → Migrate to S3/GCS/Azure Blob with locking and encryption.245- **Provider without version constraint** → Add `version = "~> X.0"` to prevent breaking upgrades.246- **Hardcoded secrets in .tf files** → Use variables with `sensitive = true`, or integrate Vault/SSM.247- **IAM policy with `"Action": "*"`** → Scope to specific actions. No wildcard actions in production.248- **Security group open to 0.0.0.0/0 on SSH/RDP** → Restrict to bastion CIDR or use SSM Session Manager.249- **No state locking** → Enable DynamoDB table for S3 backend, or use TF Cloud.250- **Resources without tags** → Add default_tags in provider block. Tags are mandatory for cost tracking.251- **Missing `prevent_destroy` on databases/storage** → Add lifecycle block to prevent accidental deletion.252253---254255## Installation256257### One-liner (any tool)258```bash259git clone https://github.com/alirezarezvani/claude-skills.git260cp -r claude-skills/engineering/terraform-patterns ~/.claude/skills/261```262263### Multi-tool install264```bash265./scripts/convert.sh --skill terraform-patterns --tool codex|gemini|cursor|windsurf|openclaw266```267268### OpenClaw269```bash270clawhub install terraform-patterns271```272273---274275## Related Skills276277- **senior-devops** — Broader DevOps scope (CI/CD, monitoring, containerization). Complementary — use terraform-patterns for IaC-specific work, senior-devops for pipeline and infrastructure operations.278- **aws-solution-architect** — AWS architecture design. Complementary — terraform-patterns implements the infrastructure, aws-solution-architect designs it.279- **senior-security** — Application security. Complementary — terraform-patterns covers infrastructure security posture, senior-security covers application-level threats.280- **ci-cd-pipeline-builder** — Pipeline construction. Complementary — terraform-patterns defines infrastructure, ci-cd-pipeline-builder automates deployment.281282## More in this skill283284Load these only when the task needs them.285286- [references/module-patterns.md](references/module-patterns.md) — Terraform Module Design Patterns Reference287- [references/state-management.md](references/state-management.md) — Terraform State Management Reference