关于 terraform-patterns
面向基础设施团队的 Terraform 工作流技能,帮助规范模块设计、保护状态数据并审查面向生产环境的代码。它提供审查与安全命令,以及用于检查模块质量和常见配置风险的命令行分析工具。
主要功能
- 01Terraform 代码审查命令
- 02模块设计与重构指导
- 03状态及后端安全检查
- 04模块结构命令行分析器
- 05.tf 文件安全扫描器
- 06CI/CD 与漂移检测模式
适用场景
- 01审查 Terraform 文件的结构问题
- 02设计输入输出清晰的可复用模块
- 03扫描基础设施代码中的暴露密钥
- 04检查远程状态与锁定配置
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alirezarezvani/ claude-skills --skill terraform-patterns安装后在 Claude Code 中输入/terraform-patterns确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/module-patterns.mdstate-management.mdscripts/tf_module_analyzer.pytf_security_scanner.py详细介绍
Terraform 模式
可预测的基础设施。安全的状态。可组合的模块。没有漂移。
有主见的 Terraform 工作流,将杂乱的 HCL 转化为结构良好、安全、可用于生产环境的基础设施代码。涵盖模块设计、状态管理、提供商模式、安全加固以及 CI/CD 集成。
这不是 Terraform 教程,而是一套具体决策,指导你如何编写不会在凌晨 3 点出问题的基础设施代码。
斜杠命令
| 命令 | 功能 |
|---|---|
/terraform:review | 分析 Terraform 代码中的反模式、安全问题和结构问题 |
/terraform:module | 设计或重构 Terraform 模块,确保输入、输出和组合方式得当 |
/terraform:security | 审计 Terraform 代码中的安全漏洞、密钥泄露和 IAM 配置错误 |
何时激活此技能
识别用户的以下表述模式:
- "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"
- 任何涉及以下内容的请求:
.tf文件、HCL、Terraform 模块、状态管理、提供商配置、基础设施即代码
如果用户拥有 .tf 文件,或希望使用 Terraform 部署基础设施,则适用此技能。
工作流
/terraform:review — Terraform 代码审查
-
分析当前状态
- 读取目标目录中的所有
.tf文件 - 识别模块结构(扁平还是嵌套)
- 统计资源、数据源、变量和输出的数量
- 检查命名规范
- 读取目标目录中的所有
-
应用审查清单
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 -
生成报告
python3 scripts/tf_module_analyzer.py ./terraform -
运行安全扫描
python3 scripts/tf_security_scanner.py ./terraform
/terraform:module — 模块设计
-
确定模块范围
- 单一职责:一个模块对应一个逻辑分组
- 确定输入(变量)、输出和资源边界
- 决定:扁平模块(单一目录)还是嵌套模块(调用子模块)
-
应用模块设计清单
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" } -
生成模块脚手架
- 包含样板代码的输出文件结构
- 包含变量验证块
- 在适当位置添加生命周期规则
/terraform:security — 安全审计
-
代码层面审计
检查项 严重程度 修复方法 .tf文件中的硬编码密钥严重 使用设置了 sensitive = true 的变量或密钥保险库 IAM 策略使用 *操作严重 限定为特定操作和资源 安全组对端口 22/3389 开放 0.0.0.0/0 严重 限制为已知 CIDR 段,或使用 SSM/堡垒机 S3 存储桶未加密 高 添加 server_side_encryption_configuration块S3 存储桶公开访问 高 添加 aws_s3_bucket_public_access_blockRDS 未加密 高 设置 storage_encrypted = trueRDS 可公开访问 高 设置 publicly_accessible = false未启用 CloudTrail 中 添加 aws_cloudtrail资源有状态资源缺少 prevent_destroy中 添加 lifecycle { prevent_destroy = true }密钥类变量未设置 sensitive = true中 为密钥变量添加 sensitive = true -
状态安全审计
检查项 严重程度 修复方法 本地状态文件 严重 迁移到带加密的远程后端 远程状态未加密 高 在后端启用加密(SSE-S3、KMS) 未启用状态锁定 高 为 S3 启用 DynamoDB,为 TF Cloud 使用原生锁定 所有团队成员均可访问状态 中 通过 IAM 策略或 TF Cloud 团队进行限制 -
生成安全报告
python3 scripts/tf_security_scanner.py ./terraform python3 scripts/tf_security_scanner.py ./terraform --output json
工具
scripts/tf_module_analyzer.py
用于分析 Terraform 目录结构和模块质量的命令行工具。
功能特性:
- 资源与数据源计数
- 变量和输出分析(缺失描述、类型、验证)
- 命名规范检查
- 模块组合检测
- 文件结构校验
- JSON 和文本输出
用法:
# 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
用于扫描 .tf 文件中常见安全问题的命令行工具。
功能特性:
- 硬编码密钥检测(AWS 密钥、密码、令牌)
- 权限过宽的 IAM 策略检测
- 开放安全组检测(敏感端口上的 0.0.0.0/0)
- 缺失加密检查(S3、RDS、EBS)
- 公共访问检测(S3、RDS、EC2)
- 敏感变量审计
- JSON 和文本输出
用法:
# 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
模块设计模式
模式 1:扁平模块(小型/中型项目)
infrastructure/
├── main.tf # All resources
├── variables.tf # All inputs
├── outputs.tf # All outputs
├── versions.tf # Provider requirements
├── terraform.tfvars # Environment values (not committed)
└── backend.tf # Remote state configuration
适用于:单一应用、资源少于 20 个、由一个团队负责全部内容。
模式 2:嵌套模块(中型/大型项目)
infrastructure/
├── environments/
│ ├── dev/
│ │ ├── main.tf # Calls modules with dev params
│ │ ├── backend.tf # Dev state backend
│ │ └── terraform.tfvars
│ ├── staging/
│ │ └── ...
│ └── prod/
│ └── ...
├── modules/
│ ├── networking/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ ├── compute/
│ │ └── ...
│ └── database/
│ └── ...
└── versions.tf
适用于:多环境、共享基础设施模式、团队协作。
模式 3:使用 Terragrunt 的 Mono-Repo
infrastructure/
├── terragrunt.hcl # Root config
├── modules/ # Reusable modules
│ ├── vpc/
│ ├── eks/
│ └── rds/
├── dev/
│ ├── terragrunt.hcl # Dev overrides
│ ├── vpc/
│ │ └── terragrunt.hcl # Module invocation
│ └── eks/
│ └── terragrunt.hcl
└── prod/
├── terragrunt.hcl
└── ...
适用于:大规模、多环境、需要 DRY 配置、团队级隔离。
Provider 配置模式
版本锁定
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0" # Allow 5.x, block 6.0
}
random = {
source = "hashicorp/random"
version = "~> 3.5"
}
}
}
通过别名实现多区域
provider "aws" {
region = "us-east-1"
}
provider "aws" {
alias = "west"
region = "us-west-2"
}
resource "aws_s3_bucket" "primary" {
bucket = "my-app-primary"
}
resource "aws_s3_bucket" "replica" {
provider = aws.west
bucket = "my-app-replica"
}
通过 Assume Role 实现多账户
provider "aws" {
alias = "production"
region = "us-east-1"
assume_role {
role_arn = "arn:aws:iam::PROD_ACCOUNT_ID:role/TerraformRole"
}
}
状态管理决策树
Single developer, small project?
├── Yes → Local state (but migrate to remote ASAP)
└── No
├── Using Terraform Cloud/Enterprise?
│ └── Yes → TF Cloud native backend (built-in locking, encryption, RBAC)
└── No
├── AWS?
│ └── S3 + DynamoDB (encryption, locking, versioning)
├── GCP?
│ └── GCS bucket (native locking, encryption)
├── Azure?
│ └── Azure Blob Storage (native locking, encryption)
└── Other?
└── Consul or PostgreSQL backend
Environment isolation strategy:
├── Separate state files per environment (recommended)
│ ├── Option A: Separate directories (dev/, staging/, prod/)
│ └── Option B: Terraform workspaces (simpler but less isolation)
└── Single state file for all environments (never do this)
CI/CD 集成模式
GitHub Actions Plan/Apply
# .github/workflows/terraform.yml
name: Terraform
on:
pull_request:
paths: ['terraform/**']
push:
branches: [main]
paths: ['terraform/**']
jobs:
plan:
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: terraform validate
- run: terraform plan -out=tfplan
- run: terraform show -json tfplan > plan.json
# Post plan as PR comment
apply:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
environment: production
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: terraform apply -auto-approve
漂移检测
# Run on schedule to detect drift
name: Drift Detection
on:
schedule:
- cron: '0 6 * * 1-5' # Weekdays at 6 AM
jobs:
detect:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: |
terraform plan -detailed-exitcode -out=drift.tfplan 2>&1 | tee drift.log
EXIT_CODE=$?
if [ $EXIT_CODE -eq 2 ]; then
echo "DRIFT DETECTED — review drift.log"
# Send alert (Slack, PagerDuty, etc.)
fi
主动提醒
无需用户提问,主动标记以下问题:
- 未配置远程后端 → 迁移到带锁定和加密的 S3/GCS/Azure Blob。
- Provider 未设置版本约束 → 添加
version = "~> X.0",防止破坏性升级。 - .tf 文件中存在硬编码密钥 → 使用带
sensitive = true的变量,或集成 Vault/SSM。 - IAM 策略中包含
"Action": "*"→ 限定为具体操作。生产环境中不要使用通配符操作。 - 安全组在 SSH/RDP 端口对 0.0.0.0/0 开放 → 限制为堡垒机 CIDR,或使用 SSM Session Manager。
- 未启用状态锁定 → 为 S3 后端启用 DynamoDB 表,或使用 TF Cloud。
- 资源未打标签 → 在 provider 块中添加 default_tags。标签对成本追踪是必需的。
- 数据库/存储缺少
prevent_destroy→ 添加 lifecycle 块,防止误删除。
多云 Provider 配置
当单个根模块需要同时跨 AWS、Azure 和 GCP 进行资源配置时。
Provider 别名模式
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
azurerm = {
source = "hashicorp/azurerm"
version = "~> 3.0"
}
google = {
source = "hashicorp/google"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
provider "azurerm" {
features {}
subscription_id = var.azure_subscription_id
}
provider "google" {
project = var.gcp_project_id
region = var.gcp_region
}
跨 Provider 共享变量
variable "environment" {
description = "Environment name used across all providers"
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Must be dev, staging, or prod."
}
}
locals {
common_tags = {
environment = var.environment
managed_by = "terraform"
project = var.project_name
}
}
何时使用多云
- 适合:监管要求跨 Provider 实现数据驻留,或组织已在多个云上运行工作负载。
- 不适合:"避免厂商锁定"本身不足以作为理由。多云会使运维复杂度翻倍。除非有明确的业务需求,否则优先选择单云。
OpenTofu 兼容性
OpenTofu 是 Terraform 的开源分支,由 Linux Foundation 在 MPL 2.0 许可证下维护。
从 Terraform 迁移到 OpenTofu
# 1. Install OpenTofu
brew install opentofu # macOS
snap install --classic tofu # Linux
# 2. Replace the binary — state files are compatible
tofu init # Re-initializes with OpenTofu
tofu plan # Identical plan output
tofu apply # Same apply workflow
许可证注意事项
| Terraform (1.6+) | OpenTofu | |
|---|---|---|
| 许可证 | BSL 1.1(源码可用) | MPL 2.0(开源) |
| 商业使用 | 对竞争性产品有限制 | 不受限制 |
| 社区治理 | HashiCorp | Linux Foundation |
功能对等
OpenTofu 跟进 Terraform 1.6.x 的功能。OpenTofu 独有的主要新增功能包括:
- 客户端状态加密(
tofu init -encryption) - 更早的变量/locals 求值
- Provider 定义的函数
何时选择 OpenTofu
- 你的供应链需要完全开源的许可证。
- 你希望在不使用 Terraform Cloud 的情况下实现客户端状态加密。
- 其他情况下两种工具均可使用,HCL 语法和 Provider 生态完全相同。
Infracost 集成
Infracost 会在资源创建前,根据 Terraform 代码估算云成本。
PR 工作流
# Show cost breakdown for current code
infracost breakdown --path .
# Compare cost difference between current branch and main
infracost diff --path . --compare-to infracost-base.json
GitHub Actions 成本评论
# .github/workflows/infracost.yml
name: Infracost
on: [pull_request]
jobs:
cost:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: infracost/actions/setup@v3
with:
api-key: ${{ secrets.INFRACOST_API_KEY }}
- run: infracost breakdown --path ./terraform --format json --out-file /tmp/infracost.json
- run: infracost comment github --path /tmp/infracost.json --repo $GITHUB_REPOSITORY --pull-request ${{ github.event.pull_request.number }} --github-token ${{ secrets.GITHUB_TOKEN }} --behavior update
预算阈值与成本策略
# infracost.yml — policy file
version: 2.9.0
policies:
- path: "*"
max_monthly_cost: "5000" # Fail PR if estimated cost exceeds $5,000/month
max_cost_increase: "500" # Fail PR if cost increase exceeds $500/month
导入现有基础设施
将手动创建的资源纳入 Terraform 管理。
terraform import 工作流
# 1. Write the resource block first (empty body is fine)
# main.tf:
# resource "aws_s3_bucket" "legacy" {}
# 2. Import the resource into state
terraform import aws_s3_bucket.legacy my-existing-bucket-name
# 3. Run plan to see attribute diff
terraform plan
# 4. Fill in the resource block until plan shows no changes
批量导入并生成配置(Terraform 1.5+)
# Generate HCL for imported resources
terraform plan -generate-config-out=generated.tf
# Review generated.tf, then move resources into proper files
常见陷阱
- 导入后资源漂移:导入的资源可能包含 Terraform 未管理的属性。请立即运行
terraform plan,并解决每一项差异。 - State 操作:使用
terraform state mv重命名或重新组织资源。使用terraform state rm在不销毁资源的情况下将其移除。进行任何 State 操作前,务必先备份:terraform state pull > backup.tfstate。 - 敏感默认值:导入的资源可能在 State 中暴露机密信息。请限制 State 的访问权限并启用加密。
Terragrunt 模式
Terragrunt 是 Terraform 的轻量封装,为多环境配置提供 DRY(不重复自己)的能力。
根目录 terragrunt.hcl(共享配置)
# terragrunt.hcl (root)
remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
config = {
bucket = "my-org-terraform-state"
key = "${path_relative_to_include()}/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
子目录 terragrunt.hcl(环境覆盖)
# prod/vpc/terragrunt.hcl
include "root" {
path = find_in_parent_folders()
}
terraform {
source = "../../modules/vpc"
}
inputs = {
environment = "prod"
cidr_block = "10.0.0.0/16"
}
模块之间的依赖关系
# prod/eks/terragrunt.hcl
dependency "vpc" {
config_path = "../vpc"
}
inputs = {
vpc_id = dependency.vpc.outputs.vpc_id
subnet_ids = dependency.vpc.outputs.private_subnet_ids
}
Terragrunt 何时有价值
- 适用:3 个及以上环境且模块结构相同、共享后端配置,或存在跨模块依赖。
- 不适用:只有单一环境、团队规模较小,或基于目录的简单隔离已经够用。Terragrunt 会增加学习成本,并需要额外管理一个二进制文件。
安装
一行命令(适用于任何工具)
git clone https://github.com/alirezarezvani/claude-skills.git
cp -r claude-skills/engineering/terraform-patterns ~/.claude/skills/
多工具安装
./scripts/convert.sh --skill terraform-patterns --tool codex|gemini|cursor|windsurf|openclaw
OpenClaw
clawhub install terraform-patterns
相关 Skills
- senior-devops:涵盖范围更广的 DevOps(CI/CD、监控、容器化)。两者互补:IaC 相关工作使用 terraform-patterns,流水线与基础设施运维使用 senior-devops。
- aws-solution-architect:AWS 架构设计。两者互补:terraform-patterns 负责实现基础设施,aws-solution-architect 负责设计基础设施。
- senior-security:应用安全。两者互补:terraform-patterns 覆盖基础设施安全态势,senior-security 覆盖应用层威胁。
- ci-cd-pipeline-builder:流水线构建。两者互补:terraform-patterns 定义基础设施,ci-cd-pipeline-builder 负责自动化部署。