关于 iac-terraform
iac-terraform 是使用 Terraform 和 Terragrunt 开发及部署基础设施的指南与模板集,涵盖模块创建、状态管理、质量检查、故障排查和 CI/CD 工作流。
主要功能
- 01Terraform 模块脚手架与验证
- 02状态检查与漂移检测
- 03Terraform 和 Terragrunt 工作流
- 04代码质量与安全检查
- 05CI/CD 工作流模板
- 06故障排查参考资料
适用场景
- 01创建并验证可复用的 Terraform 模块
- 02变更前检查基础设施状态
- 03审查 Terraform 代码质量与安全性
- 04配置 Terraform 或 Terragrunt 的 CI/CD
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ahmedasmar/ devops-claude-skills --skill iac-terraform安装后在 Claude Code 中输入/iac-terraform确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/templates/MODULE_TEMPLATE.mdassets/workflows/github-actions-terraform.ymlgithub-actions-terragrunt.ymlgitlab-ci-terraform.ymlreferences/best_practices.mdcost_optimization.mdtroubleshooting.mdscripts/init_module.pyvalidate_module.py详细介绍
基础设施即代码 - Terraform 和 Terragrunt
关于使用 Terraform 和 Terragrunt 实现基础设施即代码的全面指南,涵盖从开发到生产部署的全过程。
核心工作流
1. 新建基础设施
工作流决策树:
Is this reusable across environments/projects?
├─ Yes → Create a Terraform module
│ └─ See "Creating Terraform Modules" below
└─ No → Create environment-specific configuration
└─ See "Environment Configuration" below
创建 Terraform 模块
构建可复用的基础设施时:
- 使用脚本搭建新模块:
python3 scripts/init_module.py my-module-name
这会自动创建:
- 标准模块文件结构
- 格式规范的模板文件
- 示例目录
- 含有文档的 README
-
使用模块模板结构:
- 完整结构请参见
assets/templates/MODULE_TEMPLATE.md - 必需文件:
main.tf、variables.tf、outputs.tf、versions.tf、README.md - 推荐:包含可运行示例的
examples/目录
- 完整结构请参见
-
遵循模块最佳实践:
- 单一职责——一个模块,一个用途
- 为可选变量设置合理的默认值
- 为所有变量和输出提供完整说明
- 使用
validation块验证输入 - 使用
sensitive = true标记敏感值
-
验证模块:
python3 scripts/validate_module.py /path/to/module
此操作会检查:
- 必需文件是否存在
- 变量是否包含说明和类型
- 输出是否包含说明
- README 是否存在且内容完整
- 是否遵循命名规范
- 敏感值是否已正确标记
- 测试模块:
cd examples/complete
terraform init
terraform plan
- 编写模块文档:
- 使用 terraform-docs 自动生成:
terraform-docs markdown . > README.md - 包含用法示例
- 记录所有输入和输出
- 使用 terraform-docs 自动生成:
关键模块模式:
有关以下内容,请参见 references/best_practices.md 中的“模块设计”部分:
- 可组合性模式
- 变量组织
- 输出设计
- 模块版本管理策略
环境配置
配置特定环境的基础设施时:
- 按环境组织结构:
environments/
├── dev/
├── staging/
└── prod/
- 采用一致的文件组织方式:
environment/
├── main.tf # Resource definitions
├── variables.tf # Variable declarations
├── terraform.tfvars # Default values (committed)
├── secrets.auto.tfvars # Sensitive values (.gitignore)
├── backend.tf # State configuration
├── outputs.tf # Output values
└── versions.tf # Version constraints
- 引用模块:
module "vpc" {
source = "git::https://github.com/company/terraform-modules.git//vpc?ref=v1.2.0"
name = "${var.environment}-vpc"
vpc_cidr = var.vpc_cidr
environment = var.environment
}
2. 状态管理与检查
检查状态的时机:
- 进行重大更改之前
- 调查偏差
- 调试资源问题
- 审计基础设施
检查状态并确认运行状况:
# List all managed resources
terraform state list
# Show detailed state for a specific resource
terraform state show <resource_address>
# Show full state summary (all resources, outputs, providers)
terraform show
检查偏差:
# Exit code 0 = no changes, 1 = error, 2 = drift detected
terraform plan -detailed-exitcode
状态操作:
# List all resources
terraform state list
# Show specific resource
terraform state show aws_instance.web
# Remove from state (doesn't destroy)
terraform state rm aws_instance.web
# Move/rename resource
terraform state mv aws_instance.web aws_instance.web_server
# Import existing resource
terraform import aws_instance.web i-1234567890abcdef0
状态最佳实践: 有关以下内容,请参见 references/best_practices.md 中的“状态管理”部分:
- 远程后端设置(S3 + DynamoDB)
- 状态文件组织策略
- 加密与安全
- 备份和恢复流程
3. 标准 Terraform 工作流
# 1. Initialize (first time or after module changes)
terraform init
# 2. Format code
terraform fmt -recursive
# 3. Validate syntax
terraform validate
# 4. Plan changes (always review!)
terraform plan -out=tfplan
# 5. Apply changes
terraform apply tfplan
# 6. Verify outputs
terraform output
使用 Terragrunt:
# Run for single module
terragrunt plan
terragrunt apply
# Run for all modules in directory tree
terragrunt run-all plan
terragrunt run-all apply
4. 故障排除
遇到错误时:
-
阅读完整的错误消息——不要跳过细节
-
查阅
references/troubleshooting.md,其中涵盖:- 状态锁定错误
- 状态偏差/损坏
- Provider 身份验证失败
- 资源错误(已存在、依赖项错误、超时)
- 模块源问题
- Terragrunt 特有问题(依赖循环、钩子)
- 性能问题
-
必要时启用调试日志:
export TF_LOG=DEBUG
export TF_LOG_PATH=terraform-debug.log
terraform plan
- 隔离问题:
# Test specific resource
terraform plan -target=aws_instance.web
terraform apply -target=aws_instance.web
- 常见快速修复:
状态已锁定(完整解决指南:references/troubleshooting.md → 状态锁定错误):
# Verify no one else running, then:
terraform force-unlock <lock-id>
Provider 缓存问题:
rm -rf .terraform
terraform init -upgrade
模块缓存问题:
rm -rf .terraform/modules
terraform init
5. 代码审查与质量
提交之前:
- 格式化代码:
terraform fmt -recursive
- 验证语法:
terraform validate
- 使用 tflint 检查:
tflint --module
- 使用 checkov 扫描安全问题:
checkov -d .
- 验证模块:
python3 scripts/validate_module.py modules/vpc
- 生成文档:
terraform-docs markdown modules/vpc > modules/vpc/README.md
审查清单:
- 所有变量均有说明
- 敏感值已标记为敏感
- 输出均有说明
- 资源遵循命名规范
- 没有硬编码的值(使用变量)
- README 内容完整且为最新版本
- 示例目录存在且可正常使用
- 已指定版本约束
- 遵循安全最佳实践
全面指南请参见 references/best_practices.md。
Terragrunt 模式
项目结构
terragrunt-project/
├── terragrunt.hcl # Root config
├── account.hcl # Account-level vars
├── region.hcl # Region-level vars
└── environments/
├── dev/
│ ├── env.hcl # Environment vars
│ └── us-east-1/
│ ├── vpc/
│ │ └── terragrunt.hcl
│ └── eks/
│ └── terragrunt.hcl
└── prod/
└── us-east-1/
├── vpc/
└── eks/
依赖管理
# In eks/terragrunt.hcl
dependency "vpc" {
config_path = "../vpc"
# Mock outputs for plan/validate
mock_outputs = {
vpc_id = "vpc-mock"
subnet_ids = ["subnet-mock"]
}
mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}
inputs = {
vpc_id = dependency.vpc.outputs.vpc_id
subnet_ids = dependency.vpc.outputs.private_subnet_ids
}
常见模式
请参阅 assets/templates/MODULE_TEMPLATE.md,其中包含完整的 Terragrunt 配置模板,包括:
- 带有提供程序生成配置的根目录 terragrunt.hcl
- 远程状态配置
- 模块级 terragrunt.hcl 模式
- 依赖项处理
参考文档
references/best_practices.md— 项目结构、状态管理、模块设计、安全性、CI/CD 集成references/troubleshooting.md— 状态锁定错误、配置漂移、提供程序问题、资源错误、Terragrunt 特有问题references/cost_optimization.md— 规格调整、Spot/RI 策略、存储优化、成本标记、多云
CI/CD 工作流
assets/workflows/ 中提供了可直接使用的模板:
| 模板 | 平台 | 功能 |
|---|---|---|
github-actions-terraform.yml | GitHub Actions | 验证、TFLint、Checkov、在 PR 上运行 plan、在 main 上运行 apply、OIDC |
github-actions-terragrunt.yml | GitHub Actions | 检测变更的模块、并行规划、感知依赖项的 apply |
gitlab-ci-terraform.yml | GitLab CI | 多阶段流水线、制品管理、手动审批关卡 |
脚本
| 脚本 | 用途 | 用法 |
|---|---|---|
init_module.py | 使用标准结构搭建新模块 | python3 scripts/init_module.py <name> [--path ./modules] [--json] |
validate_module.py | 根据最佳实践验证模块 | python3 scripts/validate_module.py <path> |
资源
templates/MODULE_TEMPLATE.md— 完整的模块模板,包含文件结构、示例和 Terragrunt 配置
快速参考
基本命令
# Initialize
terraform init
terraform init -upgrade # Update providers
# Validate
terraform validate
terraform fmt -recursive
# Plan
terraform plan
terraform plan -out=tfplan
# Apply
terraform apply
terraform apply tfplan
terraform apply -auto-approve # CI/CD only
# State
terraform state list
terraform state show <resource>
terraform state rm <resource>
terraform state mv <old> <new>
# Import
terraform import <resource_address> <resource_id>
# Destroy
terraform destroy
terraform destroy -target=<resource>
# Outputs
terraform output
terraform output <output_name>
Terragrunt 命令
# Single module
terragrunt init
terragrunt plan
terragrunt apply
# All modules
terragrunt run-all plan
terragrunt run-all apply
terragrunt run-all destroy
# With specific modules
terragrunt run-all apply --terragrunt-include-dir vpc --terragrunt-include-dir eks