关于 terraform-validator
terraform-validator 是面向 Terraform 配置维护者的验证技能,涵盖格式、语法、静态分析与安全扫描,并要求按步骤查阅文档和生成报告。
主要功能
- 01Terraform 格式化与语法验证
- 02TFLint 静态检查
- 03Checkov 安全扫描
- 04提供商与模块信息提取
- 05按检查结果生成报告
适用场景
- 01提交前检查 Terraform 配置
- 02排查配置错误与误配置
- 03扫描基础设施代码安全问题
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ akin-ozer/ cc-devops-skills --skill terraform-validator安装后在 Claude Code 中输入/terraform-validator确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/advanced_features.mdbest_practices.mdcommon_errors.mdsecurity_checklist.mdscripts/extract_tf_info_wrapper.shextract_tf_info.pyinstall_checkov.shrun_checkov.shtests/.terraform.lock.hclsample.tftest_regression.sh详细介绍
Terraform Validator
用于验证、检查和测试 Terraform 配置的综合工具包,提供语法验证、安全扫描和智能文档查询的自动化工作流。
⚠️ 关键要求检查清单
停止:你必须按顺序完成以下步骤。不得跳过任何必需步骤。
| 步骤 | 操作 | 必需 |
|---|---|---|
| 1 | 运行 bash scripts/extract_tf_info_wrapper.sh <path> | ✅ 必需 |
| 2 | 使用 Context7 查询所有提供商(显式和隐式);如果未找到,则使用 WebSearch 作为后备方案 | ✅ 必需 |
| 3 | 阅读 references/security_checklist.md | ✅ 必需 |
| 4 | 阅读 references/best_practices.md | ✅ 必需 |
| 5 | 运行 terraform fmt | ✅ 必需 |
| 6 | 运行 tflint(如果不可用,则注明已跳过) | 推荐 |
| 7 | 运行 terraform init(如果尚未初始化) | ✅ 必需 |
| 8 | 运行 terraform validate | ✅ 必需 |
| 9 | 运行 bash scripts/run_checkov.sh <path> | ✅ 必需 |
| 10 | 将发现的问题与 security_checklist.md 中的章节交叉核对 | ✅ 必需 |
| 11 | 生成并引用参考文件的报告 | ✅ 必需 |
| 12 | 运行回归测试(bash tests/test_regression.sh) | ✅ 必需 |
| 13 | 运行轻量级 CI 检查(bash -n、py_compile、smoke) | ✅ 必需 |
重要: 步骤 3-4(阅读参考文件)必须在运行安全扫描之前完成。参考文件包含修复模式,报告中必须引用这些内容。
Context7 后备方案: 如果 Context7 没有某个提供商的资料(常见于:random、null、local、time、tls),请使用 WebSearch 搜索:
"terraform-provider-{name} hashicorp documentation"
何时使用此技能
- 处理 Terraform 文件(
.tf、.tfvars、.tfstate) - 验证 Terraform 配置的语法和结构
- 检查和格式化 HCL 代码
- 使用
terraform plan执行试运行测试 - 调试 Terraform 错误或配置错误
- 了解自定义 Terraform 提供商或模块
- 对 Terraform 配置进行安全验证
外部文档
| 工具 | 文档 |
|---|---|
| Terraform | developer.hashicorp.com/terraform |
| TFLint | github.com/terraform-linters/tflint |
| Checkov | checkov.io |
| Trivy | aquasecurity.github.io/trivy |
验证工作流
重要: 请按顺序遵循此工作流。除非明确标记为可选,否则每个步骤都必须执行。
1. Identify Terraform files in scope
├─> Single file, directory, or multi-environment
2. Extract Provider/Module Info (REQUIRED)
├─> MUST run: bash scripts/extract_tf_info_wrapper.sh <path>
├─> Parse output for providers and modules
└─> Use for Context7 documentation lookup
3. Lookup Provider Documentation (REQUIRED)
├─> For EACH provider detected:
│ ├─> mcp__context7__resolve-library-id with "terraform-provider-{name}"
│ ├─> mcp__context7__query-docs for version-specific guidance
│ └─> If NOT found in Context7: WebSearch fallback (see below)
└─> Note any custom/private providers for WebSearch
4. Read Reference Files (REQUIRED before validation)
├─> MUST READ: references/security_checklist.md (before security scan)
├─> MUST READ: references/best_practices.md (for structure validation)
└─> Reference common_errors.md if errors occur
5. Format and Lint (REQUIRED)
├─> MUST run: terraform fmt -recursive (auto-fix formatting)
├─> MUST run: terraform fmt -check -recursive (verify no drift)
├─> RUN: tflint (or note as skipped if unavailable)
└─> Report formatting issues
6. Syntax Validation (REQUIRED)
├─> MUST run: terraform init (if not initialized)
├─> MUST run: terraform validate
└─> Report syntax errors (consult common_errors.md)
7. Security Scanning (REQUIRED)
├─> MUST run: bash scripts/run_checkov.sh <path>
├─> Analyze policy violations against security_checklist.md
└─> Suggest remediations from reference
8. Dry-Run Testing (if credentials available)
├─> terraform plan
├─> Analyze planned changes
└─> Report potential issues
9. Regression and Wrapper Determinism Checks (REQUIRED)
├─> MUST run: bash tests/test_regression.sh
├─> Confirms parser error handling returns non-zero
├─> Confirms implicit provider detection for docs lookup
├─> Confirms wrapper argument handling is deterministic
└─> Confirms checkov wrapper preserves scanner exit code
10. Lightweight CI Checks (REQUIRED)
├─> MUST run: bash -n scripts/*.sh
├─> MUST run: python3 -m py_compile scripts/*.py
├─> MUST run: smoke check for extract wrapper on sample fixture
└─> Record command outputs and exit codes
11. Generate Comprehensive Report
├─> Include all findings with severity
├─> Reference best_practices.md for recommendations
└─> Offer to fix issues if appropriate
必须阅读的参考文件
验证期间,你必须阅读以下参考文件:
| 时机 | 参考文件 | 操作 |
|---|---|---|
| 安全扫描前 | references/security_checklist.md | 阅读以了解安全检查和修复模式 |
| 验证期间 | references/best_practices.md | 阅读以验证项目结构、命名和模式 |
| 出现错误时 | references/common_errors.md | 阅读以查找特定错误消息的解决方案 |
| 使用 Terraform 1.10+ 时 | references/advanced_features.md | 阅读以了解临时值、操作和列表资源 |
必须使用的脚本
你必须使用这些包装脚本,而不是直接调用工具:
| 任务 | 脚本 | 命令 |
|---|---|---|
| 提取提供商/模块信息 | extract_tf_info_wrapper.sh | bash scripts/extract_tf_info_wrapper.sh <path> |
| 运行安全扫描 | run_checkov.sh | bash scripts/run_checkov.sh <path> |
| 安装 checkov(如果缺失) | install_checkov.sh | bash scripts/install_checkov.sh install |
注意:
extract_tf_info_wrapper.sh会自动处理 python-hcl2 依赖项。如果系统 Python 缺少python-hcl2,脚本会默认在~/.cache/terraform-validator/下创建或复用缓存虚拟环境。
脚本运行上下文(必需)
- 默认工作目录:
devops-skills-plugin/skills/terraform-validator - 如果从其他位置运行,请使用脚本的绝对路径:
bash /absolute/path/to/terraform-validator/scripts/extract_tf_info_wrapper.sh <path>bash /absolute/path/to/terraform-validator/scripts/run_checkov.sh <path>bash /absolute/path/to/terraform-validator/scripts/install_checkov.sh install
Context7 提供商文档查询(必需)
对于检测到的每个提供商,都必须通过 Context7 查询文档:
1. Run extract_tf_info_wrapper.sh to get provider list
2. For each provider (e.g., "aws", "google", "azurerm"):
a. Call: mcp__context7__resolve-library-id with "terraform-provider-{name}"
b. Call: mcp__context7__query-docs with the resolved ID
c. Note version-specific features and constraints
3. Include relevant provider guidance in validation report
AWS 提供商示例:
mcp__context7__resolve-library-id("terraform-provider-aws")
mcp__context7__query-docs(context7CompatibleLibraryID, "best practices")
Context7 查询失败时回退到 WebSearch(必需)
如果 Context7 未找到某个提供商,必须回退到 WebSearch:
1. If mcp__context7__resolve-library-id returns no results or provider not found:
a. Use WebSearch with query: "terraform-provider-{name} hashicorp documentation"
b. For specific version: "terraform-provider-{name} {version} documentation site:registry.terraform.io"
2. Common providers NOT in Context7 (use WebSearch directly):
- random (hashicorp/random)
- null (hashicorp/null)
- local (hashicorp/local)
- time (hashicorp/time)
- tls (hashicorp/tls)
3. Document in report: "Provider docs via WebSearch (not in Context7)"
WebSearch 回退示例:
# If Context7 fails for random provider:
WebSearch("terraform-provider-random hashicorp documentation site:registry.terraform.io")
注意: HashiCorp 实用工具提供商(random、null、local、time、tls、archive、external、http)可能未被 Context7 收录。请务必回退到 WebSearch。
检测隐式提供商(必需)
重要: 即使未在 required_providers 中声明,也可能使用提供商。必须检测所有提供商:
检测方法
- 显式提供商: 列在
required_providers块中(来自 extract_tf_info_wrapper.sh 的输出) - 隐式提供商: 根据资源类型前缀推断
常见隐式提供商模式
| 资源类型前缀 | 提供商名称 | Context7 查询项 |
|---|---|---|
random_* | random | terraform-provider-random |
null_* | null | terraform-provider-null |
local_* | local | terraform-provider-local |
tls_* | tls | terraform-provider-tls |
time_* | time | terraform-provider-time |
archive_* | archive | terraform-provider-archive |
http(数据源) | http | terraform-provider-http |
external(数据源) | external | terraform-provider-external |
完整提供商检测工作流
1. Parse extract_tf_info_wrapper.sh output
2. Get providers from "providers" array (explicit)
3. Get resources from "resources" array
4. For EACH resource type:
a. Extract prefix (e.g., "random" from "random_id")
b. Check if already in providers list
c. If NOT in providers: add as implicit provider
5. Perform Context7 lookup for ALL providers (explicit + implicit)
示例
如果 extract_tf_info_wrapper.sh 返回:
{
"providers": [{"name": "aws", ...}],
"resources": [
{"type": "aws_instance", ...},
{"type": "random_id", ...}
]
}
必须查询以下两项:
terraform-provider-aws(显式)terraform-provider-random(隐式——根据random_id资源检测到)
命令速查
格式化和代码检查
# Check formatting (dry-run)
terraform fmt -check -recursive .
# Apply formatting
terraform fmt -recursive .
# Run tflint (requires .tflint.hcl config)
tflint --init # Install plugins
tflint --recursive # Lint all modules
tflint --format compact # Compact output
TFLint 配置: 插件设置请参阅 TFLint Ruleset 文档。
验证配置
# Initialize (downloads providers and modules)
terraform init
# Validate syntax
terraform validate
# Validate with JSON output
terraform validate -json
安全扫描
必须使用包装脚本:
# Use the wrapper script (REQUIRED)
bash scripts/run_checkov.sh ./terraform
# With specific options
bash scripts/run_checkov.sh -f json ./terraform
bash scripts/run_checkov.sh --compact ./terraform
安全扫描详情: 运行安全扫描前,必须阅读
references/security_checklist.md,了解检查项和修复模式。
安全发现交叉引用(必需)
报告安全发现时,必须引用 security_checklist.md 中的具体章节:
交叉引用映射
| Checkov 检查模式 | security_checklist.md 章节 |
|---|---|
CKV_AWS_24(SSH 开放) | "权限过宽的安全组" |
CKV_AWS_260(HTTP 开放) | "权限过宽的安全组" |
CKV_AWS_16(RDS 加密) | "静态数据加密" |
CKV_AWS_17(RDS 公有) | "RDS 数据库" |
CKV_AWS_130(公有子网) | "网络安全" |
CKV_AWS_53-56(S3 公有访问) | "公有 S3 存储桶" |
CKV_AWS_*(IAM) | "IAM 安全" |
CKV_AWS_79(IMDSv1) | "ECS/EKS" |
| 硬编码密码 | "硬编码凭据" |
| 敏感输出 | "敏感输出暴露" |
安全发现报告模板
### Security Issue: [Check ID]
**Finding:** [Description from checkov]
**Resource:** [Resource name and file:line]
**Severity:** [HIGH/MEDIUM/LOW]
**Reference:** security_checklist.md - "[Section Name]"
**Remediation Pattern:**
[Copy relevant code example from security_checklist.md]
**Recommended Fix:**
[Specific fix for this configuration]
交叉引用报告示例
### Security Issue: CKV_AWS_24
**Finding:** Security group allows SSH from 0.0.0.0/0
**Resource:** aws_security_group.web (main.tf:47-79)
**Severity:** HIGH
**Reference:** security_checklist.md - "Overly Permissive Security Groups"
**Remediation Pattern (from reference):**
```hcl
variable "admin_cidr" {
description = "CIDR block for admin access"
type = string
}
resource "aws_security_group" "app" {
ingress {
description = "SSH from admin network only"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = [var.admin_cidr]
}
}
```
**Recommended Fix:** Replace `cidr_blocks = ["0.0.0.0/0"]` with a variable or specific CIDR range.
试运行测试
# Generate execution plan
terraform plan
# Save plan to file
terraform plan -out=tfplan
# Plan with specific var file
terraform plan -var-file="production.tfvars"
# Plan with target resource
terraform plan -target=aws_instance.example
Plan 输出符号:
+将要创建的资源-将要销毁的资源~将要修改的资源-/+将要替换的资源
处理缺失的工具
验证工具未安装时,请按以下恢复工作流操作:
恢复工作流(必需)
1. Detect missing tool
2. Inform user what is missing and why it's needed
3. Provide installation command
4. ASK user: "Would you like me to install [tool] and continue?"
5. If yes: Run installation and RERUN the validation step
6. If no: Note as skipped in report, continue with available tools
特定工具的恢复方法
如果缺少 checkov:
1. Inform: "Checkov is not installed. It's required for security scanning."
2. Ask: "Would you like me to install it? I'll use: bash scripts/install_checkov.sh install"
3. If yes: Run install script, then rerun security scan
如果缺少 tflint:
1. Inform: "TFLint is not installed. It provides advanced linting beyond terraform validate."
2. Ask: "Would you like me to install it?"
3. Provide: brew install tflint (macOS) or installation script (Linux)
如果缺少 python-hcl2:
The extract_tf_info_wrapper.sh script handles this automatically by creating
or reusing a cached venv. No user action required.
必需工具: terraform fmt、terraform init、terraform validate
完整安全验证所需: checkov
可选但建议使用: tflint
脚本
| 脚本 | 用途 | 用法 |
|---|---|---|
extract_tf_info_wrapper.sh | 解析 Terraform 文件中的提供程序和模块(自动处理依赖项) | bash scripts/extract_tf_info_wrapper.sh <path> |
extract_tf_info.py | 核心解析器(需要 python-hcl2) | 改用包装脚本 |
run_checkov.sh | 用于 Checkov 扫描的包装脚本,可提供增强的输出 | bash scripts/run_checkov.sh <path> |
install_checkov.sh | 在隔离的 venv 中安装 Checkov | bash scripts/install_checkov.sh install |
参考文档
验证工作流中必须阅读:
| 参考文档 | 阅读时机 | 内容 |
|---|---|---|
references/security_checklist.md | 安全扫描前 | 安全验证、Checkov/Trivy 用法、常见策略、修复模式 |
references/best_practices.md | 验证期间 | 项目结构、命名约定、模块设计、状态管理 |
references/common_errors.md | 出现错误时 | 包含原因和解决方案的错误数据库 |
references/advanced_features.md | 如果 Terraform >= 1.10 | 临时值(1.10+)、Actions(1.14+)、List Resources(1.14+) |
工作流示例
示例 1:验证单个文件
1. MUST: bash scripts/extract_tf_info_wrapper.sh main.tf
2. MUST: Context7 lookup for each provider detected
3. MUST: Read references/security_checklist.md
4. MUST: Read references/best_practices.md
5. RUN: terraform fmt -check main.tf
6. RUN: terraform init (if needed) && terraform validate
7. MUST: bash scripts/run_checkov.sh -f json main.tf
8. Report issues with remediation from references
9. If custom providers: WebSearch for documentation
示例 2:完整的模块验证
1. Identify all .tf files in directory
2. MUST: bash scripts/extract_tf_info_wrapper.sh ./modules/vpc/
3. MUST: Context7 lookup for ALL providers
4. MUST: Read references/security_checklist.md
5. MUST: Read references/best_practices.md
6. RUN: terraform fmt -recursive
7. RUN: tflint --recursive (or note as skipped if unavailable)
8. RUN: terraform init && terraform validate
9. MUST: bash scripts/run_checkov.sh ./modules/vpc/
10. Analyze findings against security_checklist.md
11. Validate structure against best_practices.md
12. Provide comprehensive report with references
示例 3:生产环境试运行
1. Verify terraform initialized
2. MUST: Read references/security_checklist.md (production focus)
3. RUN: terraform plan -var-file="production.tfvars"
4. Analyze for unexpected changes
5. Highlight create/modify/destroy operations
6. Flag security concerns (compare with security_checklist.md)
7. Recommend whether safe to apply
高级功能
Terraform 1.10+ 引入了用于安全管理密钥的临时值。Terraform 1.14+ 新增了用于命令式操作的 Actions,以及用于查询基础设施的 List Resources。
必须阅读: 在以下情况下阅读 references/advanced_features.md:
- 检测到 Terraform 版本 >= 1.10
- 配置使用
ephemeral块 - 配置使用
action块 - 配置使用
.tfquery.hcl文件
与其他技能集成
- k8s-yaml-validator - 用于验证 Terraform Kubernetes 提供程序
- helm-validator - Terraform 管理 Helm 发布版本时使用
- k8s-debug - 用于调试由 Terraform 配置的基础设施
注意事项
- 始终按顺序运行验证:提取信息 → 查阅文档 → 阅读参考资料 → 格式化 → lint → 验证 → 安全检查 → plan
- 必须使用包装脚本运行 extract_tf_info 和 checkov
- 修改脚本后必须运行
bash tests/test_regression.sh - 必须运行轻量级 CI 检查:
bash -n scripts/*.sh和python3 -m py_compile scripts/*.py - 相关验证步骤开始前必须阅读参考文件
- 必须通过 Context7 查阅所有提供程序的文档
- 工具缺失时必须提供恢复和重新运行方案
- 提交前务必运行 terraform fmt
- 应用前务必检查 plan 输出
- 所有提供程序和模块都应使用版本约束
- 团队协作时应使用远程状态
- 启用状态锁定,防止并发修改
完成标准
- 验证说明可以通过一条确定的命令路径端到端执行。
- 包装脚本在成功和失败时都能按预期运行(包括传递非零退出码)。
- 回归测试涵盖解析器错误处理、隐式提供程序检测、包装脚本参数处理,以及 checkov 退出码行为。
- 最终报告前,轻量级 CI 检查(
bash -n、py_compile、冒烟检查)均通过。