mcpField
T
terragrunt-validator

terragrunt-validator

github.com/akin-ozer测试与质量329666 次安装16 周前更新
代码仓库

关于 terragrunt-validator

terragrunt-validator 是面向 Terragrunt 配置维护者的验证与测试技能,覆盖格式、语法、依赖、计划及安全检查,并适配 Terragrunt 0.93+ CLI。

主要功能

  1. 01批量验证 Terragrunt 配置
  2. 02检查 HCL 输入与格式
  3. 03运行 tflint、Trivy 等检查
  4. 04识别自定义 Provider 和模块
  5. 05验证依赖图并执行计划
  6. 06支持 Stacks 与多模块操作

适用场景

  1. 01提交基础设施配置前进行检查
  2. 02排查 HCL 或依赖配置问题
  3. 03扫描基础设施代码安全风险

MCP 相关

文档说明可使用 Context7 MCP 查询检测到的自定义 Provider 和模块文档;未说明该技能提供 MCP 服务。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/akin-ozer/cc-devops-skills --skill terragrunt-validator

安装后在 Claude Code 中输入/terragrunt-validator确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

.gitignore
references/
best_practices.md
scripts/
detect_custom_resources.py
run_ci_checks.sh
validate_terragrunt.sh
test/
test_detect_custom_resources.py
test_validate_terragrunt.sh
test/infrastructure/
common.hcl
root.hcl
test/infrastructure/dev/
backend.tf
env.hcl
provider.tf
versions.tf
test/infrastructure/dev/app/
terragrunt.hcl
test/infrastructure/dev/cache/
terragrunt.hcl
test/infrastructure/dev/database/
terragrunt.hcl
test/infrastructure/dev/monitoring/
terragrunt.hcl
test/infrastructure/dev/vpc/
terragrunt.hcl
test/infrastructure/prod/
backend.tf
env.hcl
provider.tf
versions.tf
test/infrastructure/prod/database/
terragrunt.hcl
test/infrastructure/prod/monitoring/
terragrunt.hcl
test/infrastructure/prod/vpc/
terragrunt.hcl
test/infrastructure/staging/
backend.tf
env.hcl
provider.tf
versions.tf
test/infrastructure/staging/vpc/
terragrunt.hcl

详细介绍

Terragrunt 验证器

概述

此技能为 Terragrunt 配置提供全面的验证、Lint 和测试功能。Terragrunt 是 Terraform/OpenTofu 的轻量级封装,可提供额外工具,帮助保持配置 DRY(不要重复自己)、处理多个模块以及管理远程状态。

在以下情况下使用此技能:

  • 验证 Terragrunt HCL 文件(*.hcl、terragrunt.hcl、terragrunt.stack.hcl)
  • 使用 Terragrunt Stacks(unit/stack 块、terragrunt stack generate/run)
  • 使用 terragrunt plan 执行试运行测试
  • 按照最佳实践对 Terragrunt/Terraform 代码进行 Lint
  • 检测和调研自定义提供程序或模块
  • 调试 Terragrunt 配置问题
  • 检查依赖关系图
  • 格式化 HCL 文件
  • 对基础设施代码运行安全扫描(Trivy、Checkov)
  • 生成运行报告和摘要

Terragrunt 版本兼容性

此技能专为 Terragrunt 0.93+ 设计,该版本包含新版 CLI 重设计。

CLI 命令迁移参考
已弃用的命令新命令
run-allrun --all
hclfmthcl fmt
hclvalidatehcl validate
validate-inputshcl validate --inputs
graph-dependenciesdag graph
render-jsonrender --json -w
terragrunt-infoinfo print
plan-all、apply-allrun --all plan、run --all apply
0.93+ 的主要变更:
  • terragrunt run --all 取代 terragrunt run-all,用于多模块操作
  • terragrunt dag graph 取代 terragrunt graph-dependencies,用于依赖关系可视化
  • terragrunt hcl validate --inputs 取代 validate-inputs,用于输入验证
  • 可通过 terragrunt hcl fmt --check 或 terragrunt hcl validate 验证 HCL 语法
  • 完整验证需要运行 terragrunt init && terragrunt validate

如果使用较旧版本的 Terragrunt,可能需要调整某些命令。

核心功能

1. 全面验证套件

运行全面验证脚本,一次性执行所有检查:

bash scripts/validate_terragrunt.sh [TARGET_DIR]

验证内容:

  • HCL 格式(terragrunt hcl fmt --check)
  • HCL 输入验证(terragrunt hcl validate --inputs)
  • Terragrunt 配置语法
  • Terraform 配置验证
  • 使用 tflint 进行 Lint
  • 使用 Trivy(或旧版 tfsec)进行安全扫描
  • 依赖关系图验证
  • 试运行规划

环境变量:

  • SKIP_PLAN=true - 跳过 terragrunt plan 步骤
  • SKIP_SECURITY=true - 跳过安全扫描(Trivy/tfsec)
  • SKIP_LINT=true - 跳过 tflint Lint
  • SKIP_INIT=true - 验证前跳过 terragrunt init
  • SKIP_BACKEND_INIT=true - 使用 -backend=false 运行 init(适用于 CI/离线环境)
  • SOFT_FAIL_SECURITY=true - 报告安全发现,但不导致失败
  • TG_STRICT_MODE=true - 启用严格模式(弃用功能会报错)

使用示例:

# Full validation
bash scripts/validate_terragrunt.sh ./infrastructure/prod

# Skip plan generation (faster)
SKIP_PLAN=true bash scripts/validate_terragrunt.sh ./infrastructure

# Only validate, skip linting and security
SKIP_LINT=true SKIP_SECURITY=true bash scripts/validate_terragrunt.sh
2. 自定义提供程序和模块检测

使用检测脚本识别可能需要查阅文档的自定义提供程序和模块:

python3 scripts/detect_custom_resources.py [DIRECTORY] [--format text|json]

检测内容:

  • 自定义 Terraform 提供程序(非 HashiCorp)
  • 远程模块(Git、Terraform Registry、HTTP)
  • 提供程序版本
  • 模块版本和来源

输出格式:

  • text - 易于阅读的报告,并提供搜索建议
  • json - 适用于自动化的机器可读格式

检测到自定义资源时:

关键:必须查阅每个检测到的自定义资源(包括提供程序和模块)的文档。不得跳过任何一项。这是强制要求,不是可选项。

  1. 对于自定义提供程序:

    • 选项 A - WebSearch: 搜索提供程序文档
      • 查询格式:"{provider_source} terraform provider documentation version {version}"
      • 示例:"mongodb/mongodbatlas terraform provider documentation version 1.14.0"
    • 选项 B - Context7 MCP(优先): 使用 Context7 查阅结构化文档
      • 步骤 1:使用提供程序名称解析库 ID:mcp__context7__resolve-library-id(例如,“datadog terraform provider”)
      • 步骤 2:必须通过 mcp__context7__query-docs 和已解析的库 ID 获取文档
      • 使用诸如 "authentication requirements" 和 "configuration examples" 这样的查询
  2. 对于自定义模块(同等重要——不得跳过):

    • Terraform Registry 模块:
      • 使用 Context7:通过 mcp__context7__resolve-library-id 和模块名称查找(例如,“terraform-aws-modules vpc”)
      • 然后使用 mcp__context7__query-docs 获取文档
      • 或访问 https://registry.terraform.io/modules/{source}/{version}
    • Git 模块: 使用 WebSearch 搜索仓库 URL,查找 README 或文档
    • HTTP 模块: 调查来源 URL,查找文档
    • 注意与 Terraform/Terragrunt 版本的兼容性
  3. 文档查阅工作流(所有检测到的资源均必须执行):

    a) Run detect_custom_resources.py
    b) For EACH custom provider/module:
       - Note the exact version
       - Use Context7 MCP:
         1. mcp__context7__resolve-library-id with libraryName: "{provider/module name}"
         2. mcp__context7__query-docs with:
            - libraryId: "{resolved ID}"
            - query: "authentication requirements" (for auth requirements)
         3. mcp__context7__query-docs with:
            - libraryId: "{resolved ID}"
            - query: "configuration examples" (for setup requirements)
       - OR use WebSearch with version-specific queries
       - Review documentation for:
         * Required configuration blocks
         * Authentication requirements (API keys, credentials)
         * Available resources/data sources
         * Known issues or breaking changes in the version
    c) Apply learnings to validation/troubleshooting
    d) Document findings if issues are encountered
    

使用 Context7 MCP 的示例:

# 1. Detect custom resources
python3 scripts/detect_custom_resources.py ./infrastructure
# Output: Provider: datadog/datadog, Version: 3.30.0

# 2. Resolve library ID
mcp__context7__resolve-library-id with libraryName: "datadog terraform provider"
# Result: /datadog/terraform-provider-datadog

# 3. Fetch authentication docs (REQUIRED)
mcp__context7__query-docs with:
  libraryId: "/datadog/terraform-provider-datadog"
  query: "authentication requirements"

# 4. Fetch configuration docs
mcp__context7__query-docs with:
  libraryId: "/datadog/terraform-provider-datadog"
  query: "configuration examples"

使用 WebSearch 的示例:

# Detect custom resources
python3 scripts/detect_custom_resources.py ./infrastructure

# Then search for documentation:
# WebSearch: "datadog terraform provider 3.30.0 authentication configuration"
# WebSearch: "datadog terraform provider api_key app_key setup"
3. 分步验证

如需手动或细粒度验证,请使用以下单独命令:

格式验证
cd <target-directory>
terragrunt hcl fmt --check

# To auto-fix formatting
terragrunt hcl fmt
配置验证
# Check HCL syntax and formatting
terragrunt hcl fmt --check

# Note: In Terragrunt 0.93+, for deeper configuration validation,
# initialize and validate (requires actual resources/credentials):
# terragrunt init && terragrunt validate
Terraform 验证
# Initialize if needed
terragrunt init

# Validate
terragrunt validate
使用 tflint 进行代码检查
# Initialize tflint (if .tflint.hcl exists)
tflint --init

# Run linting
tflint --recursive
使用 Trivy 进行安全扫描(推荐)

注意: tfsec 已合并到 Trivy 中,不再积极维护。 所有新项目都应使用 Trivy。

# Using Trivy (recommended)
trivy config . --severity HIGH,CRITICAL

# With tfvars file
trivy config --tf-vars terraform.tfvars .

# Exclude downloaded modules
trivy config --tf-exclude-downloaded-modules .

# Legacy: Using tfsec (deprecated)
tfsec . --soft-fail
替代方案:使用 Checkov 进行安全扫描
# Scan directory
checkov -d . --framework terraform

# Scan with specific checks
checkov -d . --check CKV_AWS_21

# Output as JSON
checkov -d . --output json
依赖关系图验证
# Note: graph-dependencies command replaced with 'dag graph' in Terragrunt 0.93+
# Validate and display dependency graph
terragrunt dag graph

# Visualize dependencies (requires graphviz)
terragrunt dag graph | dot -Tpng > dependencies.png
试运行规划
# Single module
terragrunt plan

# All modules (new syntax - Terragrunt 0.93+)
terragrunt run --all plan

# Legacy syntax (deprecated)
# terragrunt run-all plan
4. 多模块操作

对于包含多个 Terragrunt 模块的项目,请使用 run --all(取代已弃用的 run-all):

# Validate all modules
terragrunt run --all validate

# Plan all modules
terragrunt run --all plan

# Apply all modules
terragrunt run --all apply

# Destroy all modules
terragrunt run --all destroy

# Format all HCL files
terragrunt hcl fmt

# With parallelism
terragrunt run --all plan --parallelism 4

# With strict mode (errors on deprecated features)
terragrunt --strict-mode run --all plan

# Or via environment variable
TG_STRICT_MODE=true terragrunt run --all plan
5. HCL 输入验证(0.93+ 新增)

验证所有必需输入均已设置,且不存在未使用的输入:

# Validate inputs
terragrunt hcl validate --inputs

# Show paths of invalid files
terragrunt hcl validate --show-config-path

# Combine with run --all to exclude invalid files
terragrunt run --all plan --queue-excludes-file <(terragrunt hcl validate --show-config-path || true)
6. 严格模式

启用严格模式,以便尽早发现已弃用的功能:

# Via CLI flag
terragrunt --strict-mode run --all plan

# Via environment variable (recommended for CI/CD)
export TG_STRICT_MODE=true
terragrunt run --all plan

# Check available strict controls
terragrunt info strict

特定的严格模式控制项:

如需更精细的控制,请使用 --strict-control 启用特定控制项:

# Enable specific strict controls
terragrunt run --all plan --strict-control cli-redesign --strict-control deprecated-commands

# Via environment variable (comma-separated)
TG_STRICT_CONTROL='cli-redesign,deprecated-commands' terragrunt run --all plan

# Available strict controls:
# - cli-redesign: Errors on deprecated CLI syntax
# - deprecated-commands: Errors on deprecated commands (run-all, hclfmt, etc.)
# - root-terragrunt-hcl: Errors when using root terragrunt.hcl (use root.hcl instead)
# - skip-dependencies-inputs: Improves performance by not reading dependency inputs
# - bare-include: Errors on bare include blocks (use named includes)
7. 新 CLI 命令(0.93+)
渲染配置
# Render configuration to JSON
terragrunt render --json

# Render and write to file
terragrunt render --json --write

# Output goes to terragrunt.rendered.json
打印信息(取代 terragrunt-info)
# Get contextual information about current configuration
terragrunt info print

# Output includes:
# - config_path
# - download_dir
# - terraform_binary
# - working_dir
查找并列出单元
# Find all units/stacks in directory
terragrunt find

# Output as JSON
terragrunt find --json

# Include dependency information
terragrunt find --json --dag

# List units (simpler output)
terragrunt list
运行摘要和报告
# Run with summary output (default in newer versions)
terragrunt run --all plan

# Disable summary output
terragrunt run --all plan --summary-disable

# Generate detailed report file
terragrunt run --all plan --report-file=report.json

# CSV format report
terragrunt run --all plan --report-file=report.csv
8. Terragrunt Stacks(v0.78.0+ 正式发布)

Terragrunt Stacks 使用 terragrunt.stack.hcl 文件,以声明式方式生成基础设施。

Stack 文件结构
# terragrunt.stack.hcl
locals {
  environment = "dev"
  aws_region  = "us-east-1"
}

# Define a unit (generates a single terragrunt.hcl)
unit "vpc" {
  source = "git::[email protected]:acme/infra-catalog.git//units/vpc?ref=v0.0.1"
  path   = "vpc"

  values = {
    environment = local.environment
    cidr        = "10.0.0.0/16"
  }
}

unit "database" {
  source = "git::[email protected]:acme/infra-catalog.git//units/database?ref=v0.0.1"
  path   = "database"

  values = {
    environment = local.environment
    vpc_path    = "../vpc"
  }
}

# Include reusable stacks
stack "monitoring" {
  source = "git::[email protected]:acme/infra-catalog.git//stacks/monitoring?ref=v0.0.1"
  path   = "monitoring"

  values = {
    environment = local.environment
  }
}
Stack 命令
# Generate stack (creates .terragrunt-stack directory)
terragrunt stack generate

# Generate stack without validation
terragrunt stack generate --no-stack-validate

# Run command on all stack units
terragrunt stack run plan
terragrunt stack run apply

# Clean generated stack directories
terragrunt stack clean

# Get stack outputs
terragrunt stack output
Stack 验证控制

使用 no_validation 属性跳过特定单元的验证:

unit "experimental" {
  source = "git::[email protected]:acme/infra-catalog.git//units/experimental?ref=v0.0.1"
  path   = "experimental"

  # Skip validation for this unit (useful for incomplete/experimental units)
  no_validation = true

  values = {
    environment = local.environment
  }
}
Stack 的优势
  • 整洁的工作目录:生成的代码位于隐藏的 .terragrunt-stack 目录中
  • 可复用模式:只需定义一次基础设施模式,即可多次部署
  • 固定版本:不同环境可以固定到不同版本
  • 原子更新:轻松回滚模块和配置
9. Exec 命令(运行任意程序)

exec 命令允许你在具有 Terragrunt 上下文的单元上运行任意程序。这对于将 tflint、checkov 或 AWS CLI 等其他工具与 Terragrunt 配置集成很有用。

# Run tflint with unit context (TF_VAR_ env vars available)
terragrunt exec -- tflint

# Run checkov against specific unit
terragrunt exec -- checkov -d .

# Run AWS CLI with unit's configuration
terragrunt exec -- aws s3 ls s3://my-bucket

# Run custom scripts with Terragrunt context
terragrunt exec -- ./scripts/validate_terragrunt.sh

# Run across all units
terragrunt run --all exec -- tflint

主要功能:

  • Terragrunt 会加载单元的输入,并将其作为带有 TF_VAR_ 前缀的环境变量提供
  • 适用于任何能够使用环境变量的程序
  • 与 Terragrunt 的身份验证上下文集成(例如 AWS 配置文件)
  • 可与 run --all 结合用于多单元操作

使用场景:

  • 在单元上下文中运行安全扫描器(checkov、trivy)
  • 按单元执行代码检查工具(tflint)
  • 使用正确凭证运行运维命令(AWS CLI)
  • 需要 Terragrunt 输入的自定义验证脚本
10. 功能标志(生产级功能)

Terragrunt 原生支持功能标志,以安全地更改基础设施。功能标志允许你在不增加风险的情况下集成未完成的工作、将发布与部署解耦,并将 IaC 演进过程编入代码。

定义功能标志
# terragrunt.hcl
feature "enable_monitoring" {
  default = false
}

feature "use_new_vpc" {
  default = true
}

inputs = {
  monitoring_enabled = feature.enable_monitoring.value
  vpc_version       = feature.use_new_vpc.value ? "v2" : "v1"
}
通过 CLI 使用功能标志
# Enable a feature flag
terragrunt plan --feature enable_monitoring=true

# Enable multiple feature flags
terragrunt plan --feature enable_monitoring=true --feature use_new_vpc=false

# Via environment variable
TG_FEATURE='enable_monitoring=true' terragrunt plan
将功能标志与 run --all 结合使用
# Apply feature flag across all units
terragrunt run --all plan --feature enable_monitoring=true

优点:

  • 安全发布:在部分基础设施上测试更改
  • 渐进式迁移:逐步启用新功能
  • A/B 测试:比较基础设施配置
  • 紧急回滚:快速禁用有问题的功能
11. 实验功能(选择启用的不稳定功能)

Terragrunt 提供实验功能系统,可在功能正式发布(GA)之前试用不稳定功能:

# Enable all experiments (not recommended for production)
terragrunt --experiment-mode run --all plan

# Enable specific experiment
terragrunt --experiment symlinks run --all plan

# Enable CAS (Content Addressable Storage) for faster cloning
terragrunt --experiment cas run --all plan

可用实验功能:

  • symlinks - 支持解析 Terragrunt 单元的符号链接
  • cas - 内容寻址存储,可加快 Git/模块克隆速度
  • filter-flag - 高级筛选功能(将在 1.0 中推出)

验证工作流

验证 Terragrunt 配置时,请遵循此工作流:

标准可执行工作流(默认路径)

使用统一的可执行路径,确保文档和脚本保持一致:

# Main validation
bash scripts/validate_terragrunt.sh <target-directory>

# Deterministic fixture tests (required after script changes)
python3 test/test_detect_custom_resources.py
bash test/test_validate_terragrunt.sh

执行要求:

  • 固件测试应具有确定性(通过/失败结果稳定)。
  • 验证/安全检查失败时必须返回非零退出码。
步骤 0:阅读最佳实践参考文档(必须首先执行)

开始验证前,你必须阅读最佳实践参考文件。这是强制要求。

# Read the best practices reference file first
if [ -f references/best_practices.md ]; then
  cat references/best_practices.md
else
  echo "WARNING: references/best_practices.md not found; continue with built-in checklist below."
fi

这样可确保你了解要验证的模式、反模式和检查清单。

初步评估
  1. 了解结构:

    tree -L 3 <infrastructure-directory>
    
  2. 识别 Terragrunt 文件:

    find . -name "*.hcl" -o -name "terragrunt.hcl"
    
  3. 检测自定义资源:

    python3 scripts/detect_custom_resources.py .
    
文档查询(所有已检测到的自定义资源都必须执行)

重要:如果检测到任何自定义提供程序或模块,你必须逐一查询其文档,不能遗漏任何一个。

  1. 查询每个已检测到的自定义提供程序的文档:

    • 使用 Context7 MCP(首选):
      1. 使用提供程序名称调用 mcp__context7__resolve-library-id
      2. 使用查询内容 "authentication requirements" 调用 mcp__context7__query-docs
      3. 使用查询内容 "configuration examples" 调用 mcp__context7__query-docs
    • 或使用 WebSearch:"{provider} terraform provider {version} documentation"
  2. 查询每个已检测到的自定义模块的文档:

    • 对于 Terraform Registry 模块,使用 Context7 MCP:
      1. 使用模块名称调用 mcp__context7__resolve-library-id(例如 "terraform-aws-modules vpc")
      2. 使用相关配置查询调用 mcp__context7__query-docs
    • 对于 Git 模块:使用 WebSearch 搜索仓库 URL
    • 对于 HTTP 模块:调查源 URL,查找文档
  3. 记录每个资源的查询结果:

    • 必需的配置块
    • 身份验证要求
    • 该版本中已知的问题或重大变更
验证执行
  1. 运行全面验证:

    bash scripts/validate_terragrunt.sh <target-directory>
    
  2. 检查输出中的错误:

    • 格式错误 → 使用 terragrunt hcl fmt 修复
    • 配置错误 → 检查 terragrunt.hcl 语法和输入项
    • Terraform 验证错误 → 检查 .tf 文件或生成的配置
    • Lint 问题 → 检查 tflint 输出并修复
    • 安全问题 → 检查 Trivy/Checkov/tfsec 输出并处理
    • 依赖错误 → 检查依赖块和路径
    • 计划错误 → 检查 Terraform 配置和提供程序设置
最佳实践检查(必需——必须完成所有检查清单)

必须核验以下每个检查清单项目,并记录结果(✅ 通过或 ❌ 未通过)。核验不完整不可接受。

  1. 使用 references/best_practices.md 明确核验最佳实践:

    配置模式检查清单——逐项核验:

    [ ] Include blocks: Child modules use `include "root" { path = find_in_parent_folders("root.hcl") }`
    [ ] Named includes: All include blocks have names (not bare `include {}`)
    [ ] Root file naming: Root config is named `root.hcl` (not `terragrunt.hcl`)
    [ ] Environment configs: Environment-level configs named `env.hcl` (not `terragrunt.hcl`)
    [ ] Common variables: Shared variables in `common.hcl` read via `read_terragrunt_config()`
    

    依赖管理检查清单:

    [ ] Mock outputs: ALL dependency blocks have mock_outputs for validation
    [ ] Mock allowed commands: mock_outputs_allowed_terraform_commands includes ["validate", "plan", "init"]
    [ ] Explicit paths: Dependency config_path uses relative paths ("../vpc" not absolute)
    [ ] No circular deps: Run `terragrunt dag graph` to verify no cycles
    

    安全检查清单:

    [ ] State encryption: remote_state config has `encrypt = true`
    [ ] State locking: DynamoDB table configured for S3 backend
    [ ] No hardcoded credentials: Search for patterns like "AKIA", "password =", account IDs
    [ ] Sensitive variables: Passwords/keys use `sensitive = true` in variable blocks
    [ ] IAM roles: Provider uses assume_role instead of static credentials
    

    DRY 原则检查清单:

    [ ] Generate blocks: Provider and backend configs use `generate` blocks
    [ ] Version constraints: terragrunt_version_constraint and terraform_version_constraint set
    [ ] Reusable locals: Common values in shared files, not duplicated
    [ ] if_exists: Generate blocks use appropriate if_exists strategy
    

    运行以下快速 grep 检查:

    # Check for hardcoded AWS account IDs
    grep -r "[0-9]\{12\}" --include="*.hcl" . | grep -v mock
    
    # Check for potential credentials
    grep -ri "password\s*=" --include="*.hcl" .
    grep -ri "api_key\s*=" --include="*.hcl" .
    
    # Check for dependencies without mock_outputs
    grep -l "dependency\s" --include="*.hcl" -r . | xargs grep -L "mock_outputs"
    
    # Check for terragrunt.hcl files in non-module directories (anti-pattern)
    find . -name "terragrunt.hcl" -not -path "*/.terragrunt-cache/*" | head -20
    
故障排除
  1. 常见问题及解决方法:

问题:未找到模块

rm -rf .terragrunt-cache
terragrunt init

问题:提供程序身份验证错误

  • 检查生成文件中的提供程序配置
  • 验证环境变量或凭据
  • 通过 WebSearch 查看提供程序文档

问题:依赖错误

  • 检查依赖路径是否正确
  • 确保提供 mock_outputs 以进行验证
  • 使用 terragrunt dag graph 查看依赖关系图

问题:状态锁定错误

terragrunt force-unlock <LOCK_ID>

问题:S3 后端 dynamodb_table 弃用警告

  • 较新的 Terraform 版本可能会警告:S3 后端中的 dynamodb_table 已弃用。
  • 在与工作流兼容时,优先在后端配置中使用 use_lockfile = true。
  • 仅在需要兼容旧版时保留 dynamodb_table。

问题:未知的提供程序或模块参数

  • 重新运行自定义资源检测
  • 使用 WebSearch 查找当前文档
  • 检查版本兼容性

问题:generate 块冲突(文件已存在)

ERROR: The file path ./versions.tf already exists and was not generated by terragrunt.
Can not generate terraform file: ./versions.tf already exists

**解决方案:**当静态 .tf 文件与 Terragrunt 的 generate 块冲突时,会出现此问题。可以:

  • 删除冲突的静态文件(versions.tf、provider.tf、backend.tf)
  • 或在 generate 块中使用 if_exists = "skip",以免覆盖现有文件
# Remove conflicting files
rm -f versions.tf provider.tf backend.tf
rm -rf .terragrunt-cache

问题:根目录 terragrunt.hcl 反模式警告

WARN: Using `terragrunt.hcl` as the root of Terragrunt configurations is an anti-pattern

**解决方案:**在 Terragrunt 0.93+ 中,根配置文件应命名为 root.hcl,而不是 terragrunt.hcl。重命名该文件:

mv terragrunt.hcl root.hcl
# Update include blocks in child modules to reference root.hcl

最佳实践集成

如需详细建议,请参阅全面的最佳实践指南:

# Read the best practices reference
if [ -f references/best_practices.md ]; then
  cat references/best_practices.md
else
  echo "WARNING: references/best_practices.md not found; continue with checklist in this document."
fi

需要检查的关键最佳实践:

  • ✅ 使用 include 共享配置
  • ✅ 为依赖项提供 mock_outputs
  • ✅ 使用 generate 块配置提供程序
  • ✅ 启用状态加密和锁定
  • ✅ 使用环境变量提供动态值
  • ✅ 指定版本约束
  • ✅ 避免硬编码值
  • ✅ 使用有意义的目录结构
  • ✅ 启用安全功能(加密、IAM 角色)

验证时,检查是否存在反模式:

  • ❌ 硬编码凭据或账户 ID
  • ❌ 缺少 mock outputs
  • ❌ 目录嵌套层级过深
  • ❌ 模块间配置重复
  • ❌ 缺少版本约束
  • ❌ 状态未加密

完整示例和详细指南请参阅 references/best_practices.md。

工具要求

必需:

  • terragrunt(建议使用 >= 0.93.0,以采用新的 CLI)
  • terraform 或 opentofu(建议使用 >= 1.6.0)

可选但建议使用:

  • tflint - HCL 代码检查
  • trivy - 安全扫描(取代 tfsec)
  • checkov - 替代安全扫描器(内置 750 多项策略)
  • graphviz (dot) - 依赖关系可视化
  • jq - JSON 解析
  • python3 - 用于自定义资源检测脚本

已弃用的工具:

  • tfsec - 已并入 Trivy,不再积极维护

安装命令:

# macOS
brew install terragrunt terraform tflint trivy graphviz jq

# Install Trivy (recommended security scanner)
brew install trivy

# Install Checkov (alternative security scanner)
pip3 install checkov

# Legacy tfsec (deprecated - use trivy instead)
# brew install tfsec

# Linux - Trivy
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin

# Linux - Checkov
pip3 install checkov

# Verify installations
terragrunt --version
trivy --version
checkov --version

与 Context7 MCP 集成

如果 Context7 MCP 可用,可用它查找 provider/module 文档:

  1. 解析库 ID:

    mcp__context7__resolve-library-id with libraryName: "mongodb/mongodbatlas"
    
  2. 查询文档:

    mcp__context7__query-docs with libraryId: "/mongodb/mongodbatlas" and query: "authentication requirements"
    

这能直接提供与版本对应的文档,可作为 WebSearch 的替代方案。

自动化工作流

CI/CD 集成

使用确定性的技能级 CI 门禁作为阻断性检查:

bash scripts/run_ci_checks.sh --require-shellcheck

此门禁会运行:

  • Shell 语法检查(bash -n)
  • Python 语法检查(python3 -m py_compile)
  • Python 回归测试(test/test_detect_custom_resources.py)
  • Shell 回归测试(test/test_validate_terragrunt.sh)
  • ShellCheck 代码检查(CI 中设置 --require-shellcheck 时为必需)

通过该门禁后,在已配置 Terragrunt/Terraform 凭据的任务中运行依赖环境的验证:

#!/bin/bash
# ci-validate.sh

set -euo pipefail

echo "Running deterministic validator checks..."
bash scripts/run_ci_checks.sh --require-shellcheck

echo "Installing dependencies..."
# Install terragrunt, terraform, tflint, trivy/checkov

echo "Detecting custom resources..."
python3 scripts/detect_custom_resources.py . --format json > custom_resources.json

# Could integrate with automated documentation lookup here

echo "Running validation suite..."
SKIP_PLAN=true SKIP_BACKEND_INIT=true bash scripts/validate_terragrunt.sh .

echo "Validation complete!"
Pre-commit Hook

本地开发的 pre-commit hook 示例:

#!/bin/bash
# .git/hooks/pre-commit

# Format check
terragrunt hcl fmt --check || {
    echo "HCL formatting issues found. Run: terragrunt hcl fmt"
    exit 1
}

# Quick HCL syntax validation (Terragrunt 0.93+)
# Note: For full validation, use: terragrunt init && terragrunt validate
# But that requires credentials. HCL format check catches syntax errors.

echo "Pre-commit validation passed!"

故障排除指南

验证模式和退出语义

validate_terragrunt.sh 根据目标目录确定模式,并相应调整 Terragrunt 命令路径:

模式目录结构Terragrunt HCL 检查Terraform 检查退出语义
single目标目录中有 terragrunt.hcl(或 terragrunt.stack.hcl)terragrunt hcl validateterragrunt validate(除非跳过,否则先运行 terragrunt init)任何语法/验证失败都会以非零值退出
multi目标目录下存在嵌套单元terragrunt hcl validate --all(若不支持 --all,则回退到普通的 hcl validate)terragrunt run --all validate(除非跳过,否则先运行 run --all init)任何单元失败都会以非零值退出
root-only仅有 root.hcl,目标目录中没有单元发出警告并跳过发出警告并跳过这些跳过的步骤返回成功(0)
none没有可识别的 Terragrunt 配置文件错误错误返回非零值
调试模式

启用调试输出以排查问题:

# Terragrunt debug
TERRAGRUNT_DEBUG=1 terragrunt plan

# Terraform trace
TF_LOG=TRACE terragrunt plan
常见错误模式

“Error: Module not found”

  • 清除缓存:rm -rf .terragrunt-cache
  • 重新初始化:terragrunt init

“Error: Provider not found”

  • 检查 provider 配置
  • 运行自定义资源检测
  • 使用 WebSearch 查找正确的 provider 来源和版本
  • 验证 required_providers 块

“Error: Invalid function call”

  • 检查 Terragrunt 版本兼容性
  • 查看文档中的函数语法

“Cycle detected in dependency graph”

  • 检查依赖链
  • 考虑重构为单个模块
  • 使用数据源而非依赖项

“Error acquiring state lock”

  • 检查是否有其他进程正在运行
  • 验证 DynamoDB 表(用于 S3 后端时)
  • 确认安全后强制解锁:terragrunt force-unlock <LOCK_ID>

“Error: unknown command”(Terragrunt 0.93+)

输出解读

成功指标

✅ 所有检查均通过:

  • 所有 HCL 文件格式正确
  • 输入有效
  • Terraform 配置有效
  • 没有代码检查问题
  • 没有严重安全问题
  • 依赖关系图有效
  • Plan 已成功生成
警告指标

⚠️ 需要审查:

  • Trivy/Checkov/tfsec 发出的安全警告(非关键)
  • Lint 建议(最佳实践)
  • 已弃用的提供程序功能
  • 缺少推荐配置
错误指标

✗ 必须修复:

  • 格式错误
  • 输入无效
  • Terraform 验证失败
  • 循环依赖
  • 提供程序身份验证失败
  • 状态锁定错误

高级用法

自定义验证规则

添加 .tflint.hcl 以创建自定义 tflint 规则:

plugin "terraform" {
  enabled = true
  preset  = "recommended"
}

plugin "aws" {
  enabled = true
  version = "0.27.0"
  source  = "github.com/terraform-linters/tflint-ruleset-aws"
}

rule "terraform_naming_convention" {
  enabled = true
}
自定义安全策略

添加 .tfsec/config.yml 以创建自定义 tfsec 策略:

minimum_severity: MEDIUM
exclude:
  - AWS001  # Example: exclude specific rules
依赖关系图分析

分析复杂的依赖链:

# Generate detailed graph (Terragrunt 0.93+ syntax)
terragrunt dag graph > graph.dot

# Convert to visual format
dot -Tpng graph.dot > graph.png
dot -Tsvg graph.dot > graph.svg

# Analyze for circular dependencies
grep -A5 "cycle" <(terragrunt dag graph 2>&1)

资源

脚本
  • scripts/validate_terragrunt.sh - 综合验证套件
  • scripts/detect_custom_resources.py - 自定义提供程序/模块检测器
参考资料
  • references/best_practices.md - 全面的最佳实践指南,涵盖:
    • 目录结构模式
    • DRY 原则和配置共享
    • 依赖管理
    • 安全最佳实践
    • 测试和验证工作流
    • 应避免的常见反模式
    • 故障排除指南
外部文档

完成标准

  • 文档和脚本遵循同一套规范的可执行工作流。
  • 通过以下命令确定性地运行 Fixture:
  • python3 test/test_detect_custom_resources.py
  • bash test/test_validate_terragrunt.sh
  • 验证和安全失败均以正确的非零退出码报告。

评论

支持 Markdown