terragrunt-validator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Terragrunt Validator

Terragrunt 验证工具

Overview

概述

This skill provides comprehensive validation, linting, and testing capabilities for Terragrunt configurations. Terragrunt is a thin wrapper for Terraform/OpenTofu that provides extra tools for keeping configurations DRY (Don't Repeat Yourself), working with multiple modules, and managing remote state.
Use this skill when:
  • Validating Terragrunt HCL files (*.hcl, terragrunt.hcl, terragrunt.stack.hcl)
  • Working with Terragrunt Stacks (unit/stack blocks,
    terragrunt stack generate/run
    )
  • Performing dry-run testing with
    terragrunt plan
  • Linting Terragrunt/Terraform code for best practices
  • Detecting and researching custom providers or modules
  • Debugging Terragrunt configuration issues
  • Checking dependency graphs
  • Formatting HCL files
  • Running security scans on infrastructure code (Trivy, Checkov)
  • Generating run reports and summaries
本技能为Terragrunt配置提供全面的验证、代码检查和测试功能。Terragrunt是Terraform/OpenTofu的轻量封装工具,提供额外功能来保持配置的DRY(Don't Repeat Yourself,不要重复自己)原则、管理多模块以及处理远程状态。
适用场景:
  • 验证Terragrunt HCL文件(*.hcl、terragrunt.hcl、terragrunt.stack.hcl)
  • 操作Terragrunt Stacks(unit/stack块、
    terragrunt stack generate/run
    命令)
  • 使用
    terragrunt plan
    执行试运行测试
  • 针对最佳实践检查Terragrunt/Terraform代码
  • 检测和查找自定义provider或模块
  • 调试Terragrunt配置问题
  • 检查依赖关系图
  • 格式化HCL文件
  • 对基础设施代码进行安全扫描(Trivy、Checkov)
  • 生成运行报告和摘要

Terragrunt Version Compatibility

Terragrunt版本兼容性

This skill is designed for Terragrunt 0.93+ which includes the new CLI redesign.
本技能专为**Terragrunt 0.93+**版本设计,该版本包含全新的CLI重设计。

CLI Command Migration Reference

CLI命令迁移参考

Deprecated CommandNew Command
run-all
run --all
hclfmt
hcl fmt
hclvalidate
hcl validate
validate-inputs
hcl validate --inputs
graph-dependencies
dag graph
render-json
render --json -w
terragrunt-info
info print
plan-all
,
apply-all
run --all plan
,
run --all apply
已弃用命令新命令
run-all
run --all
hclfmt
hcl fmt
hclvalidate
hcl validate
validate-inputs
hcl validate --inputs
graph-dependencies
dag graph
render-json
render --json -w
terragrunt-info
info print
plan-all
,
apply-all
run --all plan
,
run --all apply

Key Changes in 0.93+:

0.93+版本的主要变化:

  • terragrunt run --all
    replaces
    terragrunt run-all
    for multi-module operations
  • terragrunt dag graph
    replaces
    terragrunt graph-dependencies
    for dependency visualization
  • terragrunt hcl validate --inputs
    replaces
    validate-inputs
    for input validation
  • HCL syntax validation via
    terragrunt hcl fmt --check
    or
    terragrunt hcl validate
  • Full validation requires
    terragrunt init && terragrunt validate
If using an older Terragrunt version, some commands may need adjustment.
  • 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,部分命令可能需要调整。

Core Capabilities

核心功能

1. Comprehensive Validation Suite

1. 综合验证套件

Run the comprehensive validation script to perform all checks at once:
bash
bash scripts/validate_terragrunt.sh [TARGET_DIR]
What it validates:
  • HCL formatting (
    terragrunt hcl fmt --check
    )
  • HCL input validation (
    terragrunt hcl validate --inputs
    )
  • Terragrunt configuration syntax
  • Terraform configuration validation
  • Linting with tflint
  • Security scanning with Trivy (or legacy tfsec)
  • Dependency graph validation
  • Dry-run planning
Environment variables:
  • SKIP_PLAN=true
    - Skip terragrunt plan step
  • SKIP_SECURITY=true
    - Skip security scanning (Trivy/tfsec)
  • SKIP_LINT=true
    - Skip tflint linting
  • TG_STRICT_MODE=true
    - Enable strict mode (errors on deprecated features)
Example usage:
bash
undefined
运行综合验证脚本可一次性执行所有检查:
bash
bash scripts/validate_terragrunt.sh [TARGET_DIR]
验证内容:
  • HCL格式检查(
    terragrunt hcl fmt --check
  • HCL输入验证(
    terragrunt hcl validate --inputs
  • Terragrunt配置语法
  • Terraform配置验证
  • 使用tflint进行代码检查
  • 使用Trivy(或旧版tfsec)进行安全扫描
  • 依赖关系图验证
  • 试运行规划
环境变量:
  • SKIP_PLAN=true
    - 跳过terragrunt plan步骤
  • SKIP_SECURITY=true
    - 跳过安全扫描(Trivy/tfsec)
  • SKIP_LINT=true
    - 跳过tflint代码检查
  • TG_STRICT_MODE=true
    - 启用严格模式(对已弃用功能报错)
使用示例:
bash
undefined

Full validation

完整验证

bash scripts/validate_terragrunt.sh ./infrastructure/prod
bash scripts/validate_terragrunt.sh ./infrastructure/prod

Skip plan generation (faster)

跳过规划生成(速度更快)

SKIP_PLAN=true bash scripts/validate_terragrunt.sh ./infrastructure
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
undefined
SKIP_LINT=true SKIP_SECURITY=true bash scripts/validate_terragrunt.sh
undefined

2. Custom Provider and Module Detection

2. 自定义Provider和模块检测

Use the detection script to identify custom providers and modules that may require documentation lookup:
bash
python3 scripts/detect_custom_resources.py [DIRECTORY] [--format text|json]
What it detects:
  • Custom Terraform providers (non-HashiCorp)
  • Remote modules (Git, Terraform Registry, HTTP)
  • Provider versions
  • Module versions and sources
Output formats:
  • text
    - Human-readable report with search recommendations
  • json
    - Machine-readable format for automation
When custom resources are detected:
CRITICAL: You MUST look up documentation for EVERY detected custom resource (both providers AND modules). Do NOT skip any. This is mandatory, not optional.
  1. For custom providers:
    • Option A - WebSearch: Search for provider documentation
      • Query format:
        "{provider_source} terraform provider documentation version {version}"
      • Example:
        "mongodb/mongodbatlas terraform provider documentation version 1.14.0"
    • Option B - Context7 MCP (Preferred): Use Context7 for structured documentation lookup
      • Step 1: Resolve library ID:
        mcp__context7__resolve-library-id
        with provider name (e.g., "datadog terraform provider")
      • Step 2: REQUIRED - Fetch documentation:
        mcp__context7__get-library-docs
        with the resolved library ID
      • Use
        topic: "authentication"
        or
        topic: "configuration"
        for targeted docs
  2. For custom modules (EQUALLY IMPORTANT - DO NOT SKIP):
    • Terraform Registry modules:
      • Use Context7:
        mcp__context7__resolve-library-id
        with module name (e.g., "terraform-aws-modules vpc")
      • Then fetch docs with
        mcp__context7__get-library-docs
      • Or visit
        https://registry.terraform.io/modules/{source}/{version}
    • Git modules: Use WebSearch with the repository URL to find README or documentation
    • HTTP modules: Investigate the source URL for documentation
    • Pay attention to version compatibility with your Terraform/Terragrunt version
  3. Documentation lookup workflow (MANDATORY for ALL detected resources):
    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__get-library-docs with:
            - context7CompatibleLibraryID: "{resolved ID}"
            - topic: "authentication" (for auth requirements)
            - topic: "configuration" (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
Example using Context7 MCP:
undefined
使用检测脚本识别可能需要查阅文档的自定义provider和模块:
bash
python3 scripts/detect_custom_resources.py [DIRECTORY] [--format text|json]
检测内容:
  • 自定义Terraform provider(非HashiCorp官方)
  • 远程模块(Git、Terraform Registry、HTTP)
  • Provider版本
  • 模块版本和来源
输出格式:
  • text
    - 人类可读的报告,包含搜索建议
  • json
    - 机器可读格式,用于自动化流程
检测到自定义资源时:
重要提示:你必须为每个检测到的自定义资源(包括provider和模块)查阅文档。请勿跳过任何一项,这是强制性要求。
  1. 针对自定义provider:
    • 选项A - 网络搜索: 搜索provider文档
      • 查询格式:
        "{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
        ,传入provider名称(例如"datadog terraform provider")
      • 步骤2:必须执行 - 获取文档:使用解析后的库ID执行
        mcp__context7__get-library-docs
      • 可指定
        topic: "authentication"
        topic: "configuration"
        来获取针对性文档
  2. 针对自定义模块(同样重要 - 请勿跳过):
    • Terraform Registry模块:
      • 使用Context7:执行
        mcp__context7__resolve-library-id
        ,传入模块名称(例如"terraform-aws-modules vpc")
      • 然后使用
        mcp__context7__get-library-docs
        获取文档
      • 或访问
        https://registry.terraform.io/modules/{source}/{version}
    • Git模块: 使用网络搜索,传入仓库URL查找README或文档
    • HTTP模块: 调查来源URL以获取文档
    • 注意与你的Terraform/Terragrunt版本的兼容性
  3. 文档查询流程(所有检测到的资源都必须执行):
    a) 运行detect_custom_resources.py
    b) 针对每个自定义provider/模块:
       - 记录确切版本
       - 使用Context7 MCP:
         1. 执行`mcp__context7__resolve-library-id`,参数为libraryName: "{provider/模块名称}"
         2. 执行`mcp__context7__get-library-docs`,参数包括:
            - context7CompatibleLibraryID: "{解析后的ID}"
            - topic: "authentication"(用于认证要求)
            - topic: "configuration"(用于设置要求)
       - 或使用带版本的查询词进行网络搜索
       - 查阅文档以了解:
         * 必需的配置块
         * 认证要求(API密钥、凭证)
         * 可用的资源/数据源
         * 该版本中的已知问题或破坏性变更
    c) 将所学内容应用到验证/故障排除中
    d) 若遇到问题,记录发现的内容
使用Context7 MCP的示例:
undefined

1. Detect custom resources

1. 检测自定义资源

python3 scripts/detect_custom_resources.py ./infrastructure
python3 scripts/detect_custom_resources.py ./infrastructure

Output: Provider: datadog/datadog, Version: 3.30.0

输出:Provider: datadog/datadog, Version: 3.30.0

2. Resolve library ID

2. 解析库ID

mcp__context7__resolve-library-id with libraryName: "datadog terraform provider"
mcp__context7__resolve-library-id with libraryName: "datadog terraform provider"

Result: /datadog/terraform-provider-datadog

结果:/datadog/terraform-provider-datadog

3. Fetch authentication docs (REQUIRED)

3. 获取认证文档(必需)

mcp__context7__get-library-docs with: context7CompatibleLibraryID: "/datadog/terraform-provider-datadog" topic: "authentication"
mcp__context7__get-library-docs with: context7CompatibleLibraryID: "/datadog/terraform-provider-datadog" topic: "authentication"

4. Fetch configuration docs

4. 获取配置文档

mcp__context7__get-library-docs with: context7CompatibleLibraryID: "/datadog/terraform-provider-datadog" topic: "configuration"

**Example using WebSearch:**
```bash
mcp__context7__get-library-docs with: context7CompatibleLibraryID: "/datadog/terraform-provider-datadog" topic: "configuration"

**使用网络搜索的示例:**
```bash

Detect custom resources

检测自定义资源

python3 scripts/detect_custom_resources.py ./infrastructure
python3 scripts/detect_custom_resources.py ./infrastructure

Then search for documentation:

然后搜索文档:

WebSearch: "datadog terraform provider 3.30.0 authentication configuration"

网络搜索:"datadog terraform provider 3.30.0 authentication configuration"

WebSearch: "datadog terraform provider api_key app_key setup"

网络搜索:"datadog terraform provider api_key app_key setup"

undefined
undefined

3. Step-by-Step Validation

3. 分步验证

For manual or granular validation, use these individual commands:
如需手动或精细化验证,可使用以下单独命令:

Format Validation

格式验证

bash
cd <target-directory>
terragrunt hcl fmt --check
bash
cd <target-directory>
terragrunt hcl fmt --check

To auto-fix formatting

自动修复格式问题

terragrunt hcl fmt
undefined
terragrunt hcl fmt
undefined

Configuration Validation

配置验证

bash
undefined
bash
undefined

Check HCL syntax and formatting

检查HCL语法和格式

terragrunt hcl fmt --check
terragrunt hcl fmt --check

Note: In Terragrunt 0.93+, for deeper configuration validation,

注意:在Terragrunt 0.93+版本中,如需更深入的配置验证,

initialize and validate (requires actual resources/credentials):

需要初始化并验证(需要实际资源/凭证):

terragrunt init && terragrunt validate

terragrunt init && terragrunt validate

undefined
undefined

Terraform Validation

Terraform验证

bash
undefined
bash
undefined

Initialize if needed

如需初始化

terragrunt init
terragrunt init

Validate

执行验证

terragrunt validate
undefined
terragrunt validate
undefined

Linting with tflint

使用tflint进行代码检查

bash
undefined
bash
undefined

Initialize tflint (if .tflint.hcl exists)

初始化tflint(如果存在.tflint.hcl)

tflint --init
tflint --init

Run linting

运行代码检查

tflint --recursive
undefined
tflint --recursive
undefined

Security Scanning with Trivy (Recommended)

使用Trivy进行安全扫描(推荐)

Note: tfsec has been merged into Trivy and is no longer actively maintained. Use Trivy for all new projects.
bash
undefined
注意: tfsec已合并到Trivy中,不再积极维护。 所有新项目请使用Trivy。
bash
undefined

Using Trivy (recommended)

使用Trivy(推荐)

trivy config . --severity HIGH,CRITICAL
trivy config . --severity HIGH,CRITICAL

With tfvars file

结合tfvars文件

trivy config --tf-vars terraform.tfvars .
trivy config --tf-vars terraform.tfvars .

Exclude downloaded modules

排除已下载的模块

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

Legacy: Using tfsec (deprecated)

旧版:使用tfsec(已弃用)

tfsec . --soft-fail
undefined
tfsec . --soft-fail
undefined

Alternative: Security Scanning with Checkov

替代方案:使用Checkov进行安全扫描

bash
undefined
bash
undefined

Scan directory

扫描目录

checkov -d . --framework terraform
checkov -d . --framework terraform

Scan with specific checks

使用特定规则扫描

checkov -d . --check CKV_AWS_21
checkov -d . --check CKV_AWS_21

Output as JSON

以JSON格式输出

checkov -d . --output json
undefined
checkov -d . --output json
undefined

Dependency Graph Validation

依赖关系图验证

bash
undefined
bash
undefined

Note: graph-dependencies command replaced with 'dag graph' in Terragrunt 0.93+

注意:在Terragrunt 0.93+版本中,graph-dependencies命令已被
dag graph
替代

Validate and display dependency graph

验证并显示依赖关系图

terragrunt dag graph
terragrunt dag graph

Visualize dependencies (requires graphviz)

可视化依赖关系(需要graphviz)

terragrunt dag graph | dot -Tpng > dependencies.png
undefined
terragrunt dag graph | dot -Tpng > dependencies.png
undefined

Dry-Run Planning

试运行规划

bash
undefined
bash
undefined

Single module

单个模块

terragrunt plan
terragrunt plan

All modules (new syntax - Terragrunt 0.93+)

所有模块(新语法 - Terragrunt 0.93+)

terragrunt run --all plan
terragrunt run --all plan

Legacy syntax (deprecated)

旧版语法(已弃用)

terragrunt run-all plan

terragrunt run-all plan

undefined
undefined

4. Multi-Module Operations

4. 多模块操作

For projects with multiple Terragrunt modules, use
run --all
(replaces deprecated
run-all
):
bash
undefined
对于包含多个Terragrunt模块的项目,使用
run --all
(替代已弃用的
run-all
):
bash
undefined

Validate all modules

验证所有模块

terragrunt run --all validate
terragrunt run --all validate

Plan all modules

规划所有模块

terragrunt run --all plan
terragrunt run --all plan

Apply all modules

应用所有模块

terragrunt run --all apply
terragrunt run --all apply

Destroy all modules

销毁所有模块

terragrunt run --all destroy
terragrunt run --all destroy

Format all HCL files

格式化所有HCL文件

terragrunt hcl fmt
terragrunt hcl fmt

With parallelism

并行执行

terragrunt run --all plan --parallelism 4
terragrunt run --all plan --parallelism 4

With strict mode (errors on deprecated features)

启用严格模式(对已弃用功能报错)

terragrunt --strict-mode run --all plan
terragrunt --strict-mode run --all plan

Or via environment variable

或通过环境变量启用

TG_STRICT_MODE=true terragrunt run --all plan
undefined
export TG_STRICT_MODE=true terragrunt run --all plan
undefined

5. HCL Input Validation (New in 0.93+)

5. HCL输入验证(0.93+版本新增)

Validate that all required inputs are set and no unused inputs exist:
bash
undefined
验证所有必需输入已设置且无未使用的输入:
bash
undefined

Validate inputs

验证输入

terragrunt hcl validate --inputs
terragrunt hcl validate --inputs

Show paths of invalid files

显示无效文件的路径

terragrunt hcl validate --show-config-path
terragrunt hcl validate --show-config-path

Combine with run --all to exclude invalid files

结合run --all来排除无效文件

terragrunt run --all plan --queue-excludes-file <(terragrunt hcl validate --show-config-path || true)
undefined
terragrunt run --all plan --queue-excludes-file <(terragrunt hcl validate --show-config-path || true)
undefined

6. Strict Mode

6. 严格模式

Enable strict mode to catch deprecated features early:
bash
undefined
启用严格模式可提前发现已弃用的功能:
bash
undefined

Via CLI flag

通过CLI标志启用

terragrunt --strict-mode run --all plan
terragrunt --strict-mode run --all plan

Via environment variable (recommended for CI/CD)

通过环境变量启用(推荐在CI/CD中使用)

export TG_STRICT_MODE=true terragrunt run --all plan
export TG_STRICT_MODE=true terragrunt run --all plan

Check available strict controls

查看可用的严格控制选项

terragrunt info strict

**Specific Strict Controls:**

For finer-grained control, use `--strict-control` to enable specific controls:

```bash
terragrunt info strict

**特定严格控制选项:**

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

```bash

Enable specific strict controls

启用特定严格控制选项

terragrunt run --all plan --strict-control cli-redesign --strict-control deprecated-commands
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
TG_STRICT_CONTROL='cli-redesign,deprecated-commands' terragrunt run --all plan

Available strict controls:

可用的严格控制选项:

- cli-redesign: Errors on deprecated CLI syntax

- cli-redesign: 对已弃用的CLI语法报错

- deprecated-commands: Errors on deprecated commands (run-all, hclfmt, etc.)

- deprecated-commands: 对已弃用的命令报错(run-all、hclfmt等)

- root-terragrunt-hcl: Errors when using root terragrunt.hcl (use root.hcl instead)

- root-terragrunt-hcl: 当使用root terragrunt.hcl时报错(应使用root.hcl替代)

- skip-dependencies-inputs: Improves performance by not reading dependency inputs

- skip-dependencies-inputs: 不读取依赖输入以提升性能

- bare-include: Errors on bare include blocks (use named includes)

- bare-include: 对无名称的include块报错(应使用命名include)

undefined
undefined

7. New CLI Commands (0.93+)

7. 新CLI命令(0.93+版本)

Render Configuration

渲染配置

bash
undefined
bash
undefined

Render configuration to JSON

将配置渲染为JSON

terragrunt render --json
terragrunt render --json

Render and write to file

渲染并写入文件

terragrunt render --json --write
terragrunt render --json --write

Output goes to terragrunt.rendered.json

输出文件为terragrunt.rendered.json

undefined
undefined

Info Print (replaces terragrunt-info)

信息打印(替代terragrunt-info)

bash
undefined
bash
undefined

Get contextual information about current configuration

获取当前配置的上下文信息

terragrunt info print
terragrunt info print

Output includes:

输出内容包括:

- config_path

- config_path

- download_dir

- download_dir

- terraform_binary

- terraform_binary

- working_dir

- working_dir

undefined
undefined

Find and List Units

查找和列出单元

bash
undefined
bash
undefined

Find all units/stacks in directory

查找目录中的所有单元/stack

terragrunt find
terragrunt find

Output as JSON

以JSON格式输出

terragrunt find --json
terragrunt find --json

Include dependency information

包含依赖关系信息

terragrunt find --json --dag
terragrunt find --json --dag

List units (simpler output)

列出单元(简化输出)

terragrunt list
undefined
terragrunt list
undefined

Run Summary and Reports

运行摘要和报告

bash
undefined
bash
undefined

Run with summary output (default in newer versions)

运行并输出摘要(新版本默认启用)

terragrunt run --all plan
terragrunt run --all plan

Disable summary output

禁用摘要输出

terragrunt run --all plan --summary-disable
terragrunt run --all plan --summary-disable

Generate detailed report file

生成详细报告文件

terragrunt run --all plan --report-file=report.json
terragrunt run --all plan --report-file=report.json

CSV format report

CSV格式报告

terragrunt run --all plan --report-file=report.csv
undefined
terragrunt run --all plan --report-file=report.csv
undefined

8. Terragrunt Stacks (GA in v0.78.0+)

8. Terragrunt Stacks(v0.78.0+版本正式可用)

Terragrunt Stacks provide declarative infrastructure generation using
terragrunt.stack.hcl
files.
Terragrunt Stacks通过
terragrunt.stack.hcl
文件提供声明式基础设施生成功能。

Stack File Structure

Stack文件结构

hcl
undefined
hcl
undefined

terragrunt.stack.hcl

terragrunt.stack.hcl

locals { environment = "dev" aws_region = "us-east-1" }
locals { environment = "dev" aws_region = "us-east-1" }

Define a unit (generates a single terragrunt.hcl)

定义一个单元(生成单个terragrunt.hcl)

unit "vpc" { source = "git::git@github.com: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::git@github.com:acme/infra-catalog.git//units/database?ref=v0.0.1" path = "database"
values = { environment = local.environment vpc_path = "../vpc" } }
unit "vpc" { source = "git::git@github.com: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::git@github.com:acme/infra-catalog.git//units/database?ref=v0.0.1" path = "database"
values = { environment = local.environment vpc_path = "../vpc" } }

Include reusable stacks

包含可复用的stack

stack "monitoring" { source = "git::git@github.com:acme/infra-catalog.git//stacks/monitoring?ref=v0.0.1" path = "monitoring"
values = { environment = local.environment } }
undefined
stack "monitoring" { source = "git::git@github.com:acme/infra-catalog.git//stacks/monitoring?ref=v0.0.1" path = "monitoring"
values = { environment = local.environment } }
undefined

Stack Commands

Stack命令

bash
undefined
bash
undefined

Generate stack (creates .terragrunt-stack directory)

生成stack(创建.terragrunt-stack目录)

terragrunt stack generate
terragrunt stack generate

Generate stack without validation

生成stack但不进行验证

terragrunt stack generate --no-stack-validate
terragrunt stack generate --no-stack-validate

Run command on all stack units

在所有stack单元上运行命令

terragrunt stack run plan terragrunt stack run apply
terragrunt stack run plan terragrunt stack run apply

Clean generated stack directories

清理生成的stack目录

terragrunt stack clean
terragrunt stack clean

Get stack outputs

获取stack输出

terragrunt stack output
undefined
terragrunt stack output
undefined

Stack Validation Control

Stack验证控制

Use
no_validation
attribute to skip validation for specific units:
hcl
unit "experimental" {
  source = "git::git@github.com: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
  }
}
使用
no_validation
属性跳过特定单元的验证:
hcl
unit "experimental" {
  source = "git::git@github.com:acme/infra-catalog.git//units/experimental?ref=v0.0.1"
  path   = "experimental"

  # 跳过该单元的验证(适用于未完成/实验性单元)
  no_validation = true

  values = {
    environment = local.environment
  }
}

Benefits of Stacks

Stacks的优势

  • Clean working directory: Generated code in hidden
    .terragrunt-stack
    directory
  • Reusable patterns: Define infrastructure patterns once, deploy many times
  • Version pinning: Different environments can pin different versions
  • Atomic updates: Easy rollbacks of both modules and configurations
  • 整洁的工作目录:生成的代码存储在隐藏的
    .terragrunt-stack
    目录中
  • 可复用的模式:一次定义基础设施模式,可多次部署
  • 版本固定:不同环境可固定不同版本
  • 原子更新:轻松回滚模块和配置

9. Exec Command (Run Arbitrary Programs)

9. Exec命令(运行任意程序)

The
exec
command allows you to run arbitrary programs against units with Terragrunt context. This is useful for integrating other tools like tflint, checkov, or AWS CLI with Terragrunt's configuration.
bash
undefined
exec
命令允许你在Terragrunt上下文下对单元运行任意程序。这对于将tflint、checkov或AWS CLI等其他工具与Terragrunt配置集成非常有用。
bash
undefined

Run tflint with unit context (TF_VAR_ env vars available)

在单元上下文中运行tflint(可使用TF_VAR_前缀的环境变量)

terragrunt exec -- tflint
terragrunt exec -- tflint

Run checkov against specific unit

针对特定单元运行checkov

terragrunt exec -- checkov -d .
terragrunt exec -- checkov -d .

Run AWS CLI with unit's configuration

使用单元的配置运行AWS CLI

terragrunt exec -- aws s3 ls s3://my-bucket
terragrunt exec -- aws s3 ls s3://my-bucket

Run custom scripts with Terragrunt context

在Terragrunt上下文下运行自定义脚本

terragrunt exec -- ./scripts/validate.sh
terragrunt exec -- ./scripts/validate.sh

Run across all units

在所有单元上运行

terragrunt run --all exec -- tflint

**Key Features:**
- Terragrunt loads the inputs for the unit and makes them available as `TF_VAR_` prefixed environment variables
- Works with any program that can use environment variables
- Integrates with Terragrunt's authentication context (e.g., AWS profiles)
- Can be combined with `run --all` for multi-unit operations

**Use Cases:**
- Running security scanners (checkov, trivy) with unit context
- Executing linters (tflint) per unit
- Running operational commands (AWS CLI) with correct credentials
- Custom validation scripts that need Terragrunt inputs
terragrunt run --all exec -- tflint

**主要特性:**
- Terragrunt加载单元的输入,并将其作为`TF_VAR_`前缀的环境变量提供
- 可与任何能使用环境变量的程序配合使用
- 与Terragrunt的认证上下文集成(例如AWS配置文件)
- 可与`run --all`结合用于多单元操作

**使用场景:**
- 在单元上下文中运行安全扫描器(checkov、trivy)
- 针对每个单元执行代码检查工具(tflint)
- 使用正确的凭证运行运维命令(AWS CLI)
- 运行需要Terragrunt输入的自定义验证脚本

10. Feature Flags (Production Feature)

10. 功能标志(生产特性)

Terragrunt supports first-class Feature Flags for safe infrastructure changes. Feature flags allow you to integrate incomplete work without risk, decouple release from deployment, and codify IaC evolution.
Terragrunt支持原生功能标志,用于安全地进行基础设施变更。功能标志允许你集成未完成的工作而无风险、将发布与部署解耦,并将IaC演进代码化。

Defining Feature Flags

定义功能标志

hcl
undefined
hcl
undefined

terragrunt.hcl

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" }
undefined
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" }
undefined

Using Feature Flags via CLI

通过CLI使用功能标志

bash
undefined
bash
undefined

Enable a feature flag

启用一个功能标志

terragrunt plan --feature enable_monitoring=true
terragrunt plan --feature enable_monitoring=true

Enable multiple feature flags

启用多个功能标志

terragrunt plan --feature enable_monitoring=true --feature use_new_vpc=false
terragrunt plan --feature enable_monitoring=true --feature use_new_vpc=false

Via environment variable

通过环境变量启用

TG_FEATURE='enable_monitoring=true' terragrunt plan
undefined
TG_FEATURE='enable_monitoring=true' terragrunt plan
undefined

Feature Flags with run --all

结合run --all使用功能标志

bash
undefined
bash
undefined

Apply feature flag across all units

在所有单元上应用功能标志

terragrunt run --all plan --feature enable_monitoring=true

**Benefits:**
- **Safe rollouts**: Test changes on subset of infrastructure
- **Gradual migrations**: Enable new features incrementally
- **A/B testing**: Compare infrastructure configurations
- **Emergency rollbacks**: Quickly disable problematic features
terragrunt run --all plan --feature enable_monitoring=true

**优势:**
- **安全发布**:在部分基础设施上测试变更
- **渐进式迁移**:逐步启用新功能
- **A/B测试**:比较基础设施配置
- **紧急回滚**:快速禁用有问题的功能

11. Experiments (Opt-in Unstable Features)

11. 实验性功能(可选加入的不稳定功能)

Terragrunt provides an experiments system for trying unstable features before they're GA:
bash
undefined
Terragrunt提供实验系统,可在正式发布前试用不稳定功能:
bash
undefined

Enable all experiments (not recommended for production)

启用所有实验性功能(不推荐用于生产环境)

terragrunt --experiment-mode run --all plan
terragrunt --experiment-mode run --all plan

Enable specific experiment

启用特定实验性功能

terragrunt --experiment symlinks run --all plan
terragrunt --experiment symlinks run --all plan

Enable CAS (Content Addressable Storage) for faster cloning

启用CAS(内容可寻址存储)以加快克隆速度

terragrunt --experiment cas run --all plan

**Available Experiments:**
- `symlinks` - Support symlink resolution for Terragrunt units
- `cas` - Content Addressable Storage for faster Git/module cloning
- `filter-flag` - Advanced filtering capabilities (coming in 1.0)
terragrunt --experiment cas run --all plan

**可用的实验性功能:**
- `symlinks` - 支持Terragrunt单元的符号链接解析
- `cas` - 内容可寻址存储,加快Git/模块克隆速度
- `filter-flag` - 高级过滤功能(即将在1.0版本推出)

Validation Workflow

验证工作流

Follow this workflow when validating Terragrunt configurations:
验证Terragrunt配置时,请遵循以下工作流:

Step 0: Read Best Practices Reference (MANDATORY FIRST STEP)

步骤0:阅读最佳实践参考文档(必须首先执行)

You MUST read the best practices reference file BEFORE starting validation. This is not optional.
bash
undefined
你必须在开始验证前阅读最佳实践参考文件。这不是可选步骤。
bash
undefined

Read the best practices reference file first

首先阅读最佳实践参考文件

cat references/best_practices.md

This ensures you understand the patterns, anti-patterns, and checklists you will verify.
cat references/best_practices.md

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

Initial Assessment

初始评估

  1. Understand the structure:
    bash
    tree -L 3 <infrastructure-directory>
  2. Identify Terragrunt files:
    bash
    find . -name "*.hcl" -o -name "terragrunt.hcl"
  3. Detect custom resources:
    bash
    python3 scripts/detect_custom_resources.py .
  1. 了解结构:
    bash
    tree -L 3 <infrastructure-directory>
  2. 识别Terragrunt文件:
    bash
    find . -name "*.hcl" -o -name "terragrunt.hcl"
  3. 检测自定义资源:
    bash
    python3 scripts/detect_custom_resources.py .

Documentation Lookup (MANDATORY for ALL detected custom resources)

文档查询(所有检测到的自定义资源都必须执行)

CRITICAL: If ANY custom providers or modules are detected, you MUST look up documentation for EACH ONE. Do not skip any.
  1. For EACH detected custom provider - look up documentation:
    • Use Context7 MCP (preferred):
      1. mcp__context7__resolve-library-id
        with provider name
      2. mcp__context7__get-library-docs
        with topic: "authentication"
      3. mcp__context7__get-library-docs
        with topic: "configuration"
    • OR use WebSearch:
      "{provider} terraform provider {version} documentation"
  2. For EACH detected custom module - look up documentation:
    • Use Context7 MCP for Terraform Registry modules:
      1. mcp__context7__resolve-library-id
        with module name (e.g., "terraform-aws-modules vpc")
      2. mcp__context7__get-library-docs
        with relevant topic
    • For Git modules: Use WebSearch with repository URL
    • For HTTP modules: Investigate source URL for documentation
  3. Document findings for each resource:
    • Required configuration blocks
    • Authentication requirements
    • Known issues or breaking changes in the version
重要提示: 如果检测到任何自定义provider或模块,你必须为每个资源查阅文档。请勿跳过任何一项。
  1. 针对每个检测到的自定义provider - 查阅文档:
    • 使用Context7 MCP(推荐):
      1. 执行
        mcp__context7__resolve-library-id
        ,传入provider名称
      2. 执行
        mcp__context7__get-library-docs
        ,指定topic: "authentication"
      3. 执行
        mcp__context7__get-library-docs
        ,指定topic: "configuration"
    • 或使用网络搜索:
      "{provider} terraform provider {version} documentation"
  2. 针对每个检测到的自定义模块 - 查阅文档:
    • 对于Terraform Registry模块,使用Context7 MCP:
      1. 执行
        mcp__context7__resolve-library-id
        ,传入模块名称(例如"terraform-aws-modules vpc")
      2. 执行
        mcp__context7__get-library-docs
        ,指定相关主题
    • 对于Git模块:使用网络搜索,传入仓库URL
    • 对于HTTP模块:调查来源URL以获取文档
  3. 记录每个资源的发现内容:
    • 必需的配置块
    • 认证要求
    • 该版本中的已知问题或破坏性变更

Validation Execution

验证执行

  1. Run comprehensive validation:
    bash
    bash scripts/validate_terragrunt.sh <target-directory>
  2. Review output for errors:
    • Format errors → Fix with
      terragrunt hcl fmt
    • Configuration errors → Check terragrunt.hcl syntax and inputs
    • Terraform validation errors → Check .tf files or generated configs
    • Linting issues → Review tflint output and fix
    • Security issues → Review tfsec output and address
    • Dependency errors → Check dependency blocks and paths
    • Plan errors → Review Terraform configuration and provider setup
  1. 运行综合验证:
    bash
    bash scripts/validate_terragrunt.sh <target-directory>
  2. 检查输出中的错误:
    • 格式错误 → 使用
      terragrunt hcl fmt
      修复
    • 配置错误 → 检查terragrunt.hcl语法和输入
    • Terraform验证错误 → 检查.tf文件或生成的配置
    • 代码检查问题 → 查看tflint输出并修复
    • 安全问题 → 查看tfsec输出并处理
    • 依赖错误 → 检查依赖块和路径
    • 规划错误 → 查看Terraform配置和provider设置

Best Practices Check (REQUIRED - Must Complete All Checklists)

最佳实践检查(必须执行 - 必须完成所有检查清单)

You MUST verify each checklist item below and document the result (✅ pass or ❌ fail). Incomplete verification is not acceptable.
  1. Perform explicit best practices verification using
    references/best_practices.md
    :
    Configuration Pattern Checklist - verify each item:
    [ ] 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()`
    Dependency Management Checklist:
    [ ] 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
    Security Checklist:
    [ ] 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 Principle Checklist:
    [ ] 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
    Quick grep checks to run:
    bash
    # 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. 使用
    references/best_practices.md
    执行明确的最佳实践验证:
    配置模式检查清单 - 验证每个项:
    [ ] Include块:子模块使用`include "root" { path = find_in_parent_folders("root.hcl") }`
    [ ] 命名include:所有include块都有名称(不是无名称的`include {}`)
    [ ] 根文件命名:根配置文件名为`root.hcl`(不是`terragrunt.hcl`)
    [ ] 环境配置:环境级配置文件名为`env.hcl`(不是`terragrunt.hcl`)
    [ ] 公共变量:共享变量存储在`common.hcl`中,通过`read_terragrunt_config()`读取
    依赖管理检查清单:
    [ ] 模拟输出:所有依赖块都有用于验证的mock_outputs
    [ ] 允许的模拟命令:mock_outputs_allowed_terraform_commands包含["validate", "plan", "init"]
    [ ] 明确路径:依赖的config_path使用相对路径(例如"../vpc"而非绝对路径)
    [ ] 无循环依赖:运行`terragrunt dag graph`验证是否存在循环
    安全检查清单:
    [ ] 状态加密:remote_state配置中设置`encrypt = true`
    [ ] 状态锁定:为S3后端配置DynamoDB表
    [ ] 无硬编码凭证:搜索类似"AKIA"、"password ="、账号ID的模式
    [ ] 敏感变量:密码/密钥在变量块中使用`sensitive = true`
    [ ] IAM角色:Provider使用assume_role而非静态凭证
    DRY原则检查清单:
    [ ] Generate块:Provider和后端配置使用`generate`块
    [ ] 版本约束:设置terragrunt_version_constraint和terraform_version_constraint
    [ ] 可复用的局部变量:公共值存储在共享文件中,不重复定义
    [ ] if_exists:Generate块使用合适的if_exists策略
    快速grep检查:
    bash
    # 检查硬编码的AWS账号ID
    grep -r "[0-9]\{12\}" --include="*.hcl" . | grep -v mock
    
    # 检查潜在的凭证
    grep -ri "password\s*=" --include="*.hcl" .
    grep -ri "api_key\s*=" --include="*.hcl" .
    
    # 检查没有mock_outputs的依赖块
    grep -l "dependency\s" --include="*.hcl" -r . | xargs grep -L "mock_outputs"
    
    # 检查非模块目录中的terragrunt.hcl文件(反模式)
    find . -name "terragrunt.hcl" -not -path "*/.terragrunt-cache/*" | head -20

Troubleshooting

故障排除

  1. Common issues and resolutions:
Issue: Module not found
bash
rm -rf .terragrunt-cache
terragrunt init
Issue: Provider authentication errors
  • Check provider configuration in generated files
  • Verify environment variables or credentials
  • Review provider documentation from WebSearch
Issue: Dependency errors
  • Check dependency paths are correct
  • Ensure mock_outputs are provided for validation
  • Review dependency graph with
    terragrunt dag graph
Issue: State locking errors
bash
terragrunt force-unlock <LOCK_ID>
Issue: Unknown provider or module parameters
  • Re-run custom resource detection
  • Use WebSearch to look up current documentation
  • Check version compatibility
Issue: Generate block conflicts (file already exists)
ERROR: The file path ./versions.tf already exists and was not generated by terragrunt.
Can not generate terraform file: ./versions.tf already exists
Solution: This occurs when static
.tf
files exist that conflict with Terragrunt's
generate
blocks. Either:
  • Remove the conflicting static files (
    versions.tf
    ,
    provider.tf
    ,
    backend.tf
    )
  • Or use
    if_exists = "skip"
    in the generate block to not overwrite existing files
bash
# Remove conflicting files
rm -f versions.tf provider.tf backend.tf
rm -rf .terragrunt-cache
Issue: Root terragrunt.hcl anti-pattern warning
WARN: Using `terragrunt.hcl` as the root of Terragrunt configurations is an anti-pattern
Solution: In Terragrunt 0.93+, the root configuration file should be named
root.hcl
instead of
terragrunt.hcl
. Rename the file:
bash
mv terragrunt.hcl root.hcl
# Update include blocks in child modules to reference root.hcl
  1. 常见问题及解决方法:
    问题:模块未找到
    bash
    rm -rf .terragrunt-cache
    terragrunt init
    问题:Provider认证错误
    • 检查生成文件中的Provider配置
    • 验证环境变量或凭证
    • 查阅网络搜索到的Provider文档
    问题:依赖错误
    • 检查依赖路径是否正确
    • 确保验证时提供了mock_outputs
    • 使用
      terragrunt dag graph
      查看依赖关系图
    问题:状态锁定错误
    bash
    terragrunt force-unlock <LOCK_ID>
    问题:未知的provider或模块参数
    • 重新运行自定义资源检测
    • 使用网络搜索查找最新文档
    • 检查版本兼容性
    问题:Generate块冲突(文件已存在)
    ERROR: The file path ./versions.tf already exists and was not generated by terragrunt.
    Can not generate terraform file: ./versions.tf already exists
    解决方法: 当存在与Terragrunt的
    generate
    块冲突的静态
    .tf
    文件时,会出现此错误。可选择:
    • 删除冲突的静态文件(
      versions.tf
      provider.tf
      backend.tf
    • 或在generate块中使用
      if_exists = "skip"
      以不覆盖现有文件
    bash
    # 删除冲突文件
    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
    。重命名文件:
    bash
    mv terragrunt.hcl root.hcl
    # 更新子模块中的include块以引用root.hcl

Best Practices Integration

最佳实践集成

Reference the comprehensive best practices guide for detailed recommendations:
bash
undefined
参考综合最佳实践指南获取详细建议:
bash
undefined

Read the best practices reference

阅读最佳实践参考文档

cat references/best_practices.md

**Key best practices to check:**
- ✅ Use `include` for shared configuration
- ✅ Provide mock_outputs for dependencies
- ✅ Use `generate` blocks for provider config
- ✅ Enable state encryption and locking
- ✅ Use environment variables for dynamic values
- ✅ Specify version constraints
- ✅ Avoid hardcoded values
- ✅ Use meaningful directory structure
- ✅ Enable security features (encryption, IAM roles)

**When validating, check for anti-patterns:**
- ❌ Hardcoded credentials or account IDs
- ❌ Missing mock outputs
- ❌ Overly deep directory nesting
- ❌ Duplicated configuration across modules
- ❌ Missing version constraints
- ❌ Unencrypted state

Refer to `references/best_practices.md` for complete examples and detailed guidance.
cat references/best_practices.md

**需要检查的关键最佳实践:**
- ✅ 使用`include`实现共享配置
- ✅ 为依赖提供mock_outputs
- ✅ 使用`generate`块配置Provider
- ✅ 启用状态加密和锁定
- ✅ 使用环境变量存储动态值
- ✅ 指定版本约束
- ✅ 避免硬编码值
- ✅ 使用有意义的目录结构
- ✅ 启用安全功能(加密、IAM角色)

**验证时需要检查的反模式:**
- ❌ 硬编码凭证或账号ID
- ❌ 缺少模拟输出
- ❌ 过深的目录嵌套
- ❌ 模块间重复配置
- ❌ 缺少版本约束
- ❌ 未加密的状态

请参考`references/best_practices.md`获取完整示例和详细指导。

Tool Requirements

工具要求

Required:
  • terragrunt (>= 0.93.0 recommended for new CLI)
  • terraform or opentofu (>= 1.6.0 recommended)
Optional but recommended:
  • tflint - HCL linting
  • trivy - Security scanning (replaces tfsec)
  • checkov - Alternative security scanner (750+ built-in policies)
  • graphviz (dot) - Dependency visualization
  • jq - JSON parsing
  • python3 - For custom resource detection script
Deprecated tools:
  • tfsec - Merged into Trivy, no longer actively maintained
Installation commands:
bash
undefined
必需工具:
  • terragrunt(推荐0.93.0+版本以使用新CLI)
  • terraform或opentofu(推荐1.6.0+版本)
可选但推荐的工具:
  • tflint - HCL代码检查
  • trivy - 安全扫描(替代tfsec)
  • checkov - 替代安全扫描工具(包含750+内置规则)
  • graphviz (dot) - 依赖关系可视化
  • jq - JSON解析
  • python3 - 用于自定义资源检测脚本
已弃用工具:
  • tfsec - 已合并到Trivy,不再积极维护
安装命令:
bash
undefined

macOS

macOS

brew install terragrunt terraform tflint trivy graphviz jq
brew install terragrunt terraform tflint trivy graphviz jq

Install Trivy (recommended security scanner)

安装Trivy(推荐的安全扫描器)

brew install trivy
brew install trivy

Install Checkov (alternative security scanner)

安装Checkov(替代安全扫描器)

pip3 install checkov
pip3 install checkov

Legacy tfsec (deprecated - use trivy instead)

旧版tfsec(已弃用 - 请使用trivy)

brew install tfsec

brew install tfsec

Linux - Trivy

Linux - 安装Trivy

Linux - Checkov

Linux - 安装Checkov

pip3 install checkov
pip3 install checkov

Verify installations

验证安装

terragrunt --version trivy --version checkov --version
undefined
terragrunt --version trivy --version checkov --version
undefined

Integration with Context7 MCP

与Context7 MCP的集成

If Context7 MCP is available, use it for provider/module documentation lookup:
  1. Resolve library ID:
    mcp__context7__resolve-library-id with libraryName: "mongodb/mongodbatlas"
  2. Get documentation:
    mcp__context7__get-library-docs with context7CompatibleLibraryID: "/mongodb/mongodbatlas"
This provides version-aware documentation directly, as an alternative to WebSearch.
如果Context7 MCP可用,可使用它来查找provider/模块文档:
  1. 解析库ID:
    mcp__context7__resolve-library-id with libraryName: "mongodb/mongodbatlas"
  2. 获取文档:
    mcp__context7__get-library-docs with context7CompatibleLibraryID: "/mongodb/mongodbatlas"
这可直接提供版本相关的文档,作为网络搜索的替代方案。

Automated Workflows

自动化工作流

CI/CD Integration

CI/CD集成

Example validation in CI/CD pipeline:
bash
#!/bin/bash
CI/CD流水线中的验证示例:
bash
#!/bin/bash

ci-validate.sh

ci-validate.sh

set -e
echo "Installing dependencies..."
set -e
echo "安装依赖..."

Install terragrunt, terraform, tflint, tfsec

安装terragrunt、terraform、tflint、tfsec

echo "Detecting custom resources..." python3 scripts/detect_custom_resources.py . --format json > custom_resources.json
echo "检测自定义资源..." 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 bash scripts/validate_terragrunt.sh .
echo "Validation complete!"
undefined
echo "运行验证套件..." SKIP_PLAN=true bash scripts/validate_terragrunt.sh .
echo "验证完成!"
undefined

Pre-commit Hook

预提交钩子

Example pre-commit hook for local development:
bash
#!/bin/bash
本地开发的预提交钩子示例:
bash
#!/bin/bash

.git/hooks/pre-commit

.git/hooks/pre-commit

Format check

格式检查

terragrunt hcl fmt --check || { echo "HCL formatting issues found. Run: terragrunt hcl fmt" exit 1 }
terragrunt hcl fmt --check || { echo "发现HCL格式问题。请运行:terragrunt hcl fmt" exit 1 }

Quick HCL syntax validation (Terragrunt 0.93+)

快速HCL语法验证(Terragrunt 0.93+)

Note: For full validation, use: terragrunt init && terragrunt validate

注意:如需完整验证,请使用:terragrunt init && terragrunt validate

But that requires credentials. HCL format check catches syntax errors.

但这需要凭证。HCL格式检查可捕获语法错误。

echo "Pre-commit validation passed!"
undefined
echo "预提交验证通过!"
undefined

Troubleshooting Guide

故障排除指南

Debug Mode

调试模式

Enable debug output for troubleshooting:
bash
undefined
启用调试输出以进行故障排除:
bash
undefined

Terragrunt debug

Terragrunt调试

TERRAGRUNT_DEBUG=1 terragrunt plan
TERRAGRUNT_DEBUG=1 terragrunt plan

Terraform trace

Terraform跟踪

TF_LOG=TRACE terragrunt plan
undefined
TF_LOG=TRACE terragrunt plan
undefined

Common Error Patterns

常见错误模式

"Error: Module not found"
  • Clear cache:
    rm -rf .terragrunt-cache
  • Re-initialize:
    terragrunt init
"Error: Provider not found"
  • Check provider configuration
  • Run custom resource detection
  • Use WebSearch to find correct provider source and version
  • Verify required_providers block
"Error: Invalid function call"
  • Check Terragrunt version compatibility
  • Review function syntax in documentation
"Cycle detected in dependency graph"
  • Review dependency chains
  • Consider refactoring into single module
  • Use data sources instead of dependencies
"Error acquiring state lock"
  • Check if another process is running
  • Verify DynamoDB table (for S3 backend)
  • Force unlock if safe:
    terragrunt force-unlock <LOCK_ID>
"Error: unknown command" (Terragrunt 0.93+)
"Error: Module not found"
  • 清理缓存:
    rm -rf .terragrunt-cache
  • 重新初始化:
    terragrunt init
"Error: Provider not found"
  • 检查Provider配置
  • 运行自定义资源检测
  • 使用网络搜索查找正确的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+)

Output Interpretation

输出解读

Success Indicators

成功指标

All checks passing:
  • All HCL files properly formatted
  • Inputs are valid
  • Terraform configuration is valid
  • No linting issues
  • No critical security issues
  • Valid dependency graph
  • Plan generated successfully
所有检查通过:
  • 所有HCL文件格式正确
  • 输入有效
  • Terraform配置有效
  • 无代码检查问题
  • 无严重安全问题
  • 依赖关系图有效
  • 规划生成成功

Warning Indicators

警告指标

⚠️ Review needed:
  • Security warnings from tfsec (non-critical)
  • Linting suggestions (best practices)
  • Deprecated provider features
  • Missing recommended configurations
⚠️ 需要复查:
  • tfsec的安全警告(非严重)
  • 代码检查建议(最佳实践)
  • 已弃用的Provider功能
  • 缺少推荐的配置

Error Indicators

错误指标

Must fix:
  • Format errors
  • Invalid inputs
  • Terraform validation failures
  • Circular dependencies
  • Provider authentication failures
  • State locking errors
必须修复:
  • 格式错误
  • 无效输入
  • Terraform验证失败
  • 循环依赖
  • Provider认证失败
  • 状态锁定错误

Advanced Usage

高级用法

Custom Validation Rules

自定义验证规则

Create custom tflint rules by adding
.tflint.hcl
:
hcl
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
}
通过添加
.tflint.hcl
创建自定义tflint规则:
hcl
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
}

Custom Security Policies

自定义安全策略

Create custom tfsec policies by adding
.tfsec/config.yml
:
yaml
minimum_severity: MEDIUM
exclude:
  - AWS001  # Example: exclude specific rules
通过添加
.tfsec/config.yml
创建自定义tfsec策略:
yaml
minimum_severity: MEDIUM
exclude:
  - AWS001  # 示例:排除特定规则

Dependency Graph Analysis

依赖关系图分析

Analyze complex dependency chains:
bash
undefined
分析复杂的依赖链:
bash
undefined

Generate detailed graph (Terragrunt 0.93+ syntax)

生成详细的关系图(Terragrunt 0.93+语法)

terragrunt dag graph > graph.dot
terragrunt dag graph > graph.dot

Convert to visual format

转换为可视化格式

dot -Tpng graph.dot > graph.png dot -Tsvg graph.dot > graph.svg
dot -Tpng graph.dot > graph.png dot -Tsvg graph.dot > graph.svg

Analyze for circular dependencies

分析是否存在循环依赖

grep -A5 "cycle" <(terragrunt dag graph 2>&1)
undefined
grep -A5 "cycle" <(terragrunt dag graph 2>&1)
undefined

Resources

资源

Scripts

脚本

  • scripts/validate_terragrunt.sh
    - Comprehensive validation suite
  • scripts/detect_custom_resources.py
    - Custom provider/module detector
  • scripts/validate_terragrunt.sh
    - 综合验证套件
  • scripts/detect_custom_resources.py
    - 自定义provider/模块检测器

References

参考文档

  • references/best_practices.md
    - Comprehensive best practices guide covering:
    • Directory structure patterns
    • DRY principles and configuration sharing
    • Dependency management
    • Security best practices
    • Testing and validation workflows
    • Common anti-patterns to avoid
    • Troubleshooting guides
  • references/best_practices.md
    - 综合最佳实践指南,涵盖:
    • 目录结构模式
    • DRY原则和配置共享
    • 依赖管理
    • 安全最佳实践
    • 测试和验证工作流
    • 需要避免的常见反模式
    • 故障排除指南

External Documentation

外部文档