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 |
|---|
| INLINECODE0 | Analyze Terraform code for anti-patterns, security issues, and structure problems |
| INLINECODE1 |
Design or refactor a Terraform module with proper inputs, outputs, and composition |
|
/terraform: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:review — Terraform Code Review
- 1. 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
- 2. Apply review checklist
CODEBLOCK0
- 3. Generate report
CODEBLOCK1
- 4. Run security scan
CODEBLOCK2
/terraform:module — Module Design
- 1. 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)
- 2. Apply module design checklist
CODEBLOCK3
- 3. Generate module scaffold
- Output file structure with boilerplate
- Include variable validation blocks
- Add lifecycle rules where appropriate
/terraform:security — Security Audit
- 1. 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 |
- 2. 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 |
- 3. 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:
CODEBLOCK5
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
Module Design Patterns
Pattern 1: Flat Module (Small/Medium Projects)
CODEBLOCK7
Best for: Single application, < 20 resources, one team owns everything.
Pattern 2: Nested Modules (Medium/Large Projects)
CODEBLOCK8
Best for: Multiple environments, shared infrastructure patterns, team collaboration.
Pattern 3: Mono-Repo with Terragrunt
CODEBLOCK9
Best for: Large-scale, many environments, DRY configuration, team-level isolation.
Provider Configuration Patterns
Version Pinning
CODEBLOCK10
Multi-Region with Aliases
CODEBLOCK11
Multi-Account with Assume Role
provider "aws" {
alias = "production"
region = "us-east-1"
assume_role {
role_arn = "arn:aws:iam::PROD_ACCOUNT_ID:role/TerraformRole"
}
}
State Management Decision Tree
CODEBLOCK13
CI/CD Integration Patterns
GitHub Actions Plan/Apply
CODEBLOCK14
Drift Detection
CODEBLOCK15
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)
CODEBLOCK16
Multi-tool install
CODEBLOCK17
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.
Terraform 模式
可预测的基础设施。安全的状态。可组合的模块。无漂移。
一种有主见的 Terraform 工作流程,将杂乱的 HCL 代码转变为结构清晰、安全、生产级的基础设施代码。涵盖模块设计、状态管理、提供者模式、安全加固和 CI/CD 集成。
这不是 Terraform 教程——而是一套关于如何编写不会在凌晨 3 点出问题的基础设施代码的具体决策。
斜杠命令
| 命令 | 功能 |
|---|
| /terraform:review | 分析 Terraform 代码中的反模式、安全问题和结构问题 |
| /terraform:module |
设计或重构具有适当输入、输出和组合的 Terraform 模块 |
| /terraform:security | 审计 Terraform 代码中的安全漏洞、密钥泄露和 IAM 配置错误 |
何时激活此技能
识别用户的以下模式:
- - 审查这段 Terraform 代码
- 设计一个 Terraform 模块用于...
- 我的 Terraform 状态...
- 设置远程状态后端
- 多区域 Terraform 部署
- Terraform 安全审查
- 模块结构最佳实践
- Terraform CI/CD 流水线
- 任何涉及以下内容的请求:.tf 文件、HCL、Terraform 模块、状态管理、提供者配置、基础设施即代码
如果用户有 .tf 文件或希望使用 Terraform 配置基础设施 → 此技能适用。
工作流程
/terraform:review — Terraform 代码审查
- 1. 分析当前状态
- 读取目标目录中的所有 .tf 文件
- 识别模块结构(扁平 vs 嵌套)
- 统计资源、数据源、变量、输出
- 检查命名约定
- 2. 应用审查清单
模块结构
├── 变量具有描述和类型约束
├── 输出仅暴露消费者所需的内容
├── 资源使用一致的命名:{provider}{type}{purpose}
├── 使用 locals 处理计算值和 DRY 表达式
└── 无硬编码值——所有内容参数化或放在 locals 中
状态和后端
├── 配置了远程后端(S3、GCS、Azure Blob、Terraform Cloud)
├── 启用了状态锁定(S3 使用 DynamoDB,其他使用原生)
├── 启用了静态状态加密
├── 状态中不存储密钥(或状态访问受限)
└── 为环境使用工作区或目录隔离
提供者
├── 版本约束使用悲观操作符:~> 5.0
├── 在 terraform {} 块中包含 required_providers 块
├── 为多区域或多账户使用提供者别名
└── 子模块中不包含提供者配置
安全
├── 无硬编码的密钥、密码或口令
├── IAM 遵循最小权限原则
├── 为存储、数据库、密钥启用加密
├── 安全组不过度宽松(敏感端口上无 0.0.0.0/0 入站规则)
└── 敏感变量标记为 sensitive = true
- 3. 生成报告
bash
python3 scripts/tf
moduleanalyzer.py ./terraform
- 4. 运行安全扫描
bash
python3 scripts/tf
securityscanner.py ./terraform
/terraform:module — 模块设计
- 1. 确定模块范围
- 单一职责:一个模块 = 一个逻辑分组
- 确定输入(变量)、输出和资源边界
- 决定:扁平模块(单个目录) vs 嵌套模块(调用子模块)
- 2. 应用模块设计清单
结构
├── main.tf — 主要资源
├── variables.tf — 所有输入变量,包含描述和类型
├── outputs.tf — 所有输出,包含描述
├── versions.tf — 包含 required_providers 的 terraform {} 块
├── locals.tf — 计算值和命名约定
├── data.tf — 数据源(如果有)
└── README.md — 使用示例和变量文档
变量
├── 每个变量都有:描述、类型、验证(适用时)
├── 敏感值标记为:sensitive = true
├── 为可选设置提供默认值
├── 对相关设置使用对象类型:variable config { type = object({...}) }
└── 使用 validation { condition = ... } 进行验证
输出
├── 输出 ID、ARN、端点——消费者需要的内容
├── 每个输出都包含描述
├── 标记敏感输出:sensitive = true
└── 不输出整个资源——仅输出特定属性
组合
├── 根模块调用子模块
├── 子模块从不调用其他子模块
├── 显式传递值——子模块中无隐藏的数据源查找
├── 仅根模块中包含提供者配置
└── 使用 module name { source = ./modules/name }
- 3. 生成模块脚手架
- 输出包含样板代码的文件结构
- 包含变量验证块
- 在适当位置添加生命周期规则
/terraform:security — 安全审计
- 1. 代码级审计
| 检查项 | 严重级别 | 修复方案 |
|-------|----------|-----|
| .tf 文件中的硬编码密钥 | 严重 | 使用 sensitive = true 的变量或 vault |
| 包含 * 操作的 IAM 策略 | 严重 | 限定到特定操作和资源 |
| 端口 22/3389 上包含 0.0.0.0/0 的安全组 | 严重 | 限制到已知 CIDR 块或使用 SSM/堡垒机 |
| 未加密的 S3 存储桶 | 高 | 添加 serversideencryption_configuration 块 |
| 公开访问的 S3 存储桶 | 高 | 添加 awss3bucketpublicaccess_block |
| 未加密的 RDS | 高 | 设置 storage_encrypted = true |
| 公开可访问的 RDS | 高 | 设置 publicly_accessible = false |
| 未启用 CloudTrail | 中 | 添加 aws_cloudtrail 资源 |
| 有状态资源缺少 preventdestroy | 中 | 添加 lifecycle { preventdestroy = true } |
| 密钥变量未设置 sensitive = true | 中 | 为密钥变量添加 sensitive = true |
- 2. 状态安全审计
| 检查项 | 严重级别 | 修复方案 |
|-------|----------|-----|
| 本地状态文件 | 严重 | 迁移到带加密的远程后端 |
| 未加密的远程状态 | 高 | 在后端启用加密(SSE-S3、KMS) |
| 无状态锁定 | 高 | 为 S3 启用 DynamoDB,为 TF Cloud 启用原生锁定 |
| 所有团队成员可访问状态 | 中 | 通过 IAM 策略或 TF Cloud 团队限制访问 |
- 3. 生成安全报告
bash
python3 scripts/tf
securityscanner.py ./terraform
python3 scripts/tf
securityscanner.py ./terraform --output json
工具
scripts/tfmoduleanalyzer.py
用于分析 Terraform 目录结构和模块质量的 CLI 工具。
特性:
- - 资源和数据源计数
- 变量和输出分析(缺少描述、类型、验证)
- 命名约定检查
- 模块组合检测
- 文件结构验证
- JSON 和文本输出
用法:
bash
分析 Terraform 目录
python3 scripts/tf
moduleanalyzer.py ./terraform
JSON 输出
python3 scripts/tf
moduleanalyzer.py ./terraform --output json
分析特定模块
python3 scripts/tf
moduleanalyzer.py ./modules/vpc
scripts/tfsecurityscanner.py
用于扫描 .tf 文件中常见安全问题的 CLI 工具。
特性:
- - 硬编码密钥检测(AWS 密钥、密码、令牌)
- 过度宽松的 IAM 策略检测
- 开放安全组检测(敏感端口上的 0.0.0.0/0)
- 缺少加密检查(S3、RDS、EBS)
- 公开访问检测(S3、RDS、EC2)
- 敏感变量审计
- JSON 和文本输出
用法:
bash
#