terragrunt-generator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Terragrunt Generator

Terragrunt 生成器

Overview

概述

Generate production-ready Terragrunt configurations following current best practices, naming conventions, and security standards. All generated configurations are automatically validated.
Terragrunt 2025 Features Supported:
  • Stacks - Infrastructure blueprints with
    terragrunt.stack.hcl
    (GA since v0.78.0)
  • Feature Flags - Runtime control via
    feature
    blocks
  • Exclude Blocks - Fine-grained execution control (replaces deprecated
    skip
    )
  • Errors Blocks - Advanced error handling (replaces deprecated
    retryable_errors
    )
  • OpenTofu Engine - Alternative IaC engine support
生成符合当前最佳实践、命名规范和安全标准的生产级Terragrunt配置。所有生成的配置都会自动进行验证。
支持的Terragrunt 2025特性:
  • Stacks - 基于
    terragrunt.stack.hcl
    的基础设施蓝图(自v0.78.0起正式可用)
  • Feature Flags - 通过
    feature
    块实现运行时控制
  • Exclude Blocks - 细粒度执行控制(替代已弃用的
    skip
  • Errors Blocks - 高级错误处理(替代已弃用的
    retryable_errors

Root Configuration Naming

根配置命名

RECOMMENDED: Use
root.hcl
instead of
terragrunt.hcl
for root files per migration guide.
ApproachRoot FileInclude Syntax
Modern
root.hcl
find_in_parent_folders("root.hcl")
Legacy
terragrunt.hcl
find_in_parent_folders()
推荐:根据迁移指南,根文件使用
root.hcl
而非
terragrunt.hcl
方式根文件引用语法
现代方式
root.hcl
find_in_parent_folders("root.hcl")
遗留方式
terragrunt.hcl
find_in_parent_folders()

Architecture Patterns

架构模式

CRITICAL: Before generating ANY configuration, you MUST determine the architecture pattern and understand its constraints.
关键提示:在生成任何配置之前,必须确定架构模式并了解其约束条件。

Pattern A: Multi-Environment with Environment-Agnostic Root

模式A:多环境+与环境无关的根配置

Use when: Managing multiple environments (dev/staging/prod) with shared root configuration.
Key principle:
root.hcl
is environment-agnostic - it does NOT read environment-specific files.
infrastructure/
├── root.hcl              # Environment-AGNOSTIC (no env.hcl references)
├── dev/
│   ├── env.hcl           # Environment variables (locals block)
│   ├── vpc/terragrunt.hcl
│   └── rds/terragrunt.hcl
└── prod/
    ├── env.hcl           # Environment variables (locals block)
    ├── vpc/terragrunt.hcl
    └── rds/terragrunt.hcl
Root.hcl constraints:
  • ❌ CANNOT use
    read_terragrunt_config(find_in_parent_folders("env.hcl"))
    - env.hcl doesn't exist at root level
  • ❌ CANNOT reference
    local.environment
    or
    local.aws_region
    that come from env.hcl
  • ✅ CAN use static values or
    get_env()
    for runtime configuration
  • ✅ CAN use
    ${path_relative_to_include()}
    for state keys (this works dynamically)
Child modules read env.hcl:
hcl
undefined
适用场景:管理多个环境(开发/预发布/生产)且共享根配置时。
核心原则
root.hcl
与环境无关的——它不会读取特定环境的文件。
infrastructure/
├── root.hcl              # 与环境无关(无env.hcl引用)
├── dev/
│   ├── env.hcl           # 环境变量(locals块)
│   ├── vpc/terragrunt.hcl
│   └── rds/terragrunt.hcl
└── prod/
    ├── env.hcl           # 环境变量(locals块)
    ├── vpc/terragrunt.hcl
    └── rds/terragrunt.hcl
Root.hcl约束:
  • ❌ 不能使用
    read_terragrunt_config(find_in_parent_folders("env.hcl"))
    ——根目录下不存在env.hcl
  • ❌ 不能引用来自env.hcl的
    local.environment
    local.aws_region
  • ✅ 可以使用静态值或
    get_env()
    进行运行时配置
  • ✅ 可以使用
    ${path_relative_to_include()}
    作为状态键(动态生效)
子模块读取env.hcl:
hcl
undefined

dev/vpc/terragrunt.hcl

dev/vpc/terragrunt.hcl

include "root" { path = find_in_parent_folders("root.hcl") }
locals { env = read_terragrunt_config(find_in_parent_folders("env.hcl")) }
inputs = { name = "${local.env.locals.environment}-vpc" # Works: env.hcl exists in dev/ }
undefined
include "root" { path = find_in_parent_folders("root.hcl") }
locals { env = read_terragrunt_config(find_in_parent_folders("env.hcl")) }
inputs = { name = "${local.env.locals.environment}-vpc" # 生效:dev/目录下存在env.hcl }
undefined

Pattern B: Single Environment or Environment-Aware Root

模式B:单环境或感知环境的根配置

Use when: Single environment OR all environments share the same root with environment detection.
infrastructure/
├── root.hcl              # Can be environment-aware via get_env() or directory parsing
├── account.hcl           # Account-level config (optional)
├── region.hcl            # Region-level config (optional)
└── vpc/
    └── terragrunt.hcl
Root.hcl can detect environment:
hcl
undefined
适用场景:单环境或所有环境共享同一根配置且需要检测环境时。
infrastructure/
├── root.hcl              # 可通过get_env()或目录解析感知环境
├── account.hcl           # 账户级配置(可选)
├── region.hcl            # 区域级配置(可选)
└── vpc/
    └── terragrunt.hcl
Root.hcl可检测环境:
hcl
undefined

root.hcl - environment detection via directory path

root.hcl - 通过目录路径检测环境

locals {

Parse environment from path (e.g., "prod/vpc" -> "prod")

path_parts = split("/", path_relative_to_include()) environment = local.path_parts[0]

OR use environment variable

environment = get_env("TG_ENVIRONMENT", "dev") }
undefined
locals {

从路径中解析环境(例如:"prod/vpc" -> "prod")

path_parts = split("/", path_relative_to_include()) environment = local.path_parts[0]

或使用环境变量

environment = get_env("TG_ENVIRONMENT", "dev") }
undefined

Pattern C: Shared Environment Variables (_env directory)

模式C:共享环境变量(_env目录)

Use when: Centralizing environment variables with symlinks or direct references.
infrastructure/
├── root.hcl              # Environment-AGNOSTIC
├── _env/                 # Centralized environment definitions
│   ├── prod.hcl
│   ├── staging.hcl
│   └── dev.hcl
├── prod/
│   ├── env.hcl           # Reads from _env/prod.hcl
│   └── vpc/terragrunt.hcl
└── dev/
    ├── env.hcl           # Reads from _env/dev.hcl
    └── vpc/terragrunt.hcl
env.hcl reads from _env:
hcl
undefined
适用场景:通过符号链接或直接引用集中管理环境变量时。
infrastructure/
├── root.hcl              # 与环境无关
├── _env/                 # 集中式环境定义
│   ├── prod.hcl
│   ├── staging.hcl
│   └── dev.hcl
├── prod/
│   ├── env.hcl           # 读取_env/prod.hcl
│   └── vpc/terragrunt.hcl
└── dev/
    ├── env.hcl           # 读取_env/dev.hcl
    └── vpc/terragrunt.hcl
env.hcl读取_env目录内容:
hcl
undefined

prod/env.hcl

prod/env.hcl

locals { env_vars = read_terragrunt_config("${get_repo_root()}/_env/prod.hcl")

Re-export for child modules

environment = local.env_vars.locals.environment aws_region = local.env_vars.locals.aws_region vpc_cidr = local.env_vars.locals.vpc_cidr

... other variables

}
undefined
locals { env_vars = read_terragrunt_config("${get_repo_root()}/_env/prod.hcl")

为子模块重新导出变量

environment = local.env_vars.locals.environment aws_region = local.env_vars.locals.aws_region vpc_cidr = local.env_vars.locals.vpc_cidr

... 其他变量

}
undefined

Pre-Generation Pattern Checklist

生成前模式检查清单

MANDATORY: Before writing any files, you MUST complete this checklist and OUTPUT it to the user with checkmarks filled in. This is not optional.
Output this completed checklist before generating any files:
undefined
强制要求:在编写任何文件之前,必须完成此检查清单并将其输出给用户,勾选已完成项。这是必填步骤。
在生成任何文件之前,输出已完成的检查清单:
undefined

Architecture Pattern Selection

架构模式选择

[x] Identified architecture pattern: Pattern ___ (A/B/C) [x] Root.hcl scope: [ ] environment-agnostic OR [ ] environment-aware [x] env.hcl location: ___________________ [x] Child modules access env via: ___________________ [x] Verified: No file references a path that doesn't exist from its location

**Example completed checklist:**
[x] 已确定架构模式:模式___(A/B/C) [x] Root.hcl范围:[ ] 与环境无关 OR [ ] 感知环境 [x] env.hcl位置:___________________ [x] 子模块通过以下方式访问环境变量:___________________ [x] 已验证:没有文件引用其所在位置不存在的路径

**示例已完成的检查清单:**

Architecture Pattern Selection

架构模式选择

[x] Identified architecture pattern: Pattern A (Multi-Environment with Environment-Agnostic Root) [x] Root.hcl scope: [x] environment-agnostic OR [ ] environment-aware [x] env.hcl location: dev/env.hcl, prod/env.hcl (one per environment) [x] Child modules access env via: read_terragrunt_config(find_in_parent_folders("env.hcl")) [x] Verified: No file references a path that doesn't exist from its location
undefined
[x] 已确定架构模式:模式A(多环境+与环境无关的根配置) [x] Root.hcl范围:[x] 与环境无关 OR [ ] 感知环境 [x] env.hcl位置:dev/env.hcl, prod/env.hcl(每个环境一个) [x] 子模块通过以下方式访问环境变量:read_terragrunt_config(find_in_parent_folders("env.hcl")) [x] 已验证:没有文件引用其所在位置不存在的路径
undefined

When to Use

使用场景

  • Creating new Terragrunt projects or configurations
  • Setting up multi-environment infrastructure (dev/staging/prod)
  • Implementing DRY Terraform configurations
  • Managing complex infrastructure with dependencies
  • Working with custom Terraform providers or modules
  • 创建新的Terragrunt项目或配置
  • 搭建多环境基础设施(开发/预发布/生产)
  • 实现DRY(Don't Repeat Yourself)的Terraform配置
  • 管理具有依赖关系的复杂基础设施
  • 使用自定义Terraform提供者或模块

Core Capabilities

核心功能

1. Generate Root Configuration

1. 生成根配置

Create root-level
root.hcl
or
terragrunt.hcl
with remote state, provider config, and common variables.
MANDATORY: Before generating, READ the template file:
Read: assets/templates/root/terragrunt.hcl
Template:
assets/templates/root/terragrunt.hcl
Patterns:
references/common-patterns.md
→ Root Configuration Patterns
Key placeholders to replace:
  • [BUCKET_NAME]
    ,
    [AWS_REGION]
    ,
    [DYNAMODB_TABLE]
  • [TERRAFORM_VERSION]
    ,
    [PROVIDER_NAME]
    ,
    [PROVIDER_VERSION]
  • [ENVIRONMENT]
    ,
    [PROJECT_NAME]
Root.hcl Design Principles:
  1. Environment-agnostic by default - Don't assume env.hcl exists at root level
  2. Use static values for provider/backend region - Or use
    get_env()
    for runtime config
  3. State key uses
    path_relative_to_include()
    - This automatically includes environment path
  4. Provider tags can be static - Environment-specific tags go in child modules
创建包含远程状态、提供者配置和通用变量的根级
root.hcl
terragrunt.hcl
强制要求:生成前,必须读取模板文件:
读取:assets/templates/root/terragrunt.hcl
模板
assets/templates/root/terragrunt.hcl
模式参考
references/common-patterns.md
→ 根配置模式
需要替换的关键占位符:
  • [BUCKET_NAME]
    ,
    [AWS_REGION]
    ,
    [DYNAMODB_TABLE]
  • [TERRAFORM_VERSION]
    ,
    [PROVIDER_NAME]
    ,
    [PROVIDER_VERSION]
  • [ENVIRONMENT]
    ,
    [PROJECT_NAME]
Root.hcl设计原则:
  1. 默认与环境无关 - 不要假设根目录下存在env.hcl
  2. 为提供者/后端区域使用静态值 - 或使用
    get_env()
    进行运行时配置
  3. 状态键使用
    path_relative_to_include()
    - 自动包含环境路径
  4. 提供者标签可以是静态的 - 特定环境的标签放在子模块中

2. Generate Child Module Configuration

2. 生成子模块配置

Create child modules with dependencies, mock outputs, and proper includes.
MANDATORY: Before generating, READ the template file:
Read: assets/templates/child/terragrunt.hcl
Template:
assets/templates/child/terragrunt.hcl
Patterns:
references/common-patterns.md
→ Child Module Patterns
Module source options:
  • Local:
    "../../modules/vpc"
  • Git:
    "git::https://github.com/org/repo.git//path?ref=v1.0.0"
  • Registry:
    "tfr:///terraform-aws-modules/vpc/aws?version=5.1.0"
创建包含依赖关系、模拟输出和正确引用的子模块。
强制要求:生成前,必须读取模板文件:
读取:assets/templates/child/terragrunt.hcl
模板
assets/templates/child/terragrunt.hcl
模式参考
references/common-patterns.md
→ 子模块模式
模块源选项:

3. Generate Standalone Module

3. 生成独立模块

Self-contained modules without root dependency.
MANDATORY: Before generating, READ the template file:
Read: assets/templates/module/terragrunt.hcl
Template:
assets/templates/module/terragrunt.hcl
不依赖根配置的自包含模块。
强制要求:生成前,必须读取模板文件:
读取:assets/templates/module/terragrunt.hcl
模板
assets/templates/module/terragrunt.hcl

4. Generate Multi-Environment Infrastructure

4. 生成多环境基础设施

Complete directory structures for dev/staging/prod.
MANDATORY: Before generating:
  1. Determine architecture pattern (see Architecture Patterns section)
  2. Read relevant templates for root and child modules
  3. Verify env.hcl placement and access patterns
Patterns:
references/common-patterns.md
→ Environment-Specific Patterns
Typical structure (Pattern A - Environment-Agnostic Root):
infrastructure/
├── root.hcl              # Environment-AGNOSTIC root config
├── dev/
│   ├── env.hcl           # Dev environment variables
│   └── vpc/terragrunt.hcl
└── prod/
    ├── env.hcl           # Prod environment variables
    └── vpc/terragrunt.hcl
开发/预发布/生产环境的完整目录结构。
强制要求:生成前:
  1. 确定架构模式(请参阅架构模式部分)
  2. 读取根模块和子模块的相关模板
  3. 验证env.hcl的放置位置和访问模式
模式参考
references/common-patterns.md
→ 特定环境模式
典型结构(模式A - 与环境无关的根配置):
infrastructure/
├── root.hcl              # 与环境无关的根配置
├── dev/
│   ├── env.hcl           # 开发环境变量
│   └── vpc/terragrunt.hcl
└── prod/
    ├── env.hcl           # 生产环境变量
    └── vpc/terragrunt.hcl

5. Generate Terragrunt Stacks (2025)

5. 生成Terragrunt Stacks(2025)

Infrastructure blueprints using
terragrunt.stack.hcl
.
MANDATORY: Before generating, READ the template files:
Read: assets/templates/stack/terragrunt.stack.hcl
Read: assets/templates/catalog/terragrunt.hcl
Docs: Stacks Documentation Template:
assets/templates/stack/terragrunt.stack.hcl
Catalog Template:
assets/templates/catalog/terragrunt.hcl
Patterns:
references/common-patterns.md
→ Stacks Patterns
Commands:
bash
terragrunt stack generate    # Generate unit configurations
terragrunt stack run plan    # Plan all units
terragrunt stack run apply   # Apply all units
terragrunt stack output      # Get aggregated outputs
terragrunt stack clean       # Clean generated directories
使用
terragrunt.stack.hcl
的基础设施蓝图。
强制要求:生成前,必须读取模板文件:
读取:assets/templates/stack/terragrunt.stack.hcl
读取:assets/templates/catalog/terragrunt.hcl
文档Stacks文档 模板
assets/templates/stack/terragrunt.stack.hcl
目录模板
assets/templates/catalog/terragrunt.hcl
模式参考
references/common-patterns.md
→ Stacks模式
命令:
bash
terragrunt stack generate    # 生成单元配置
terragrunt stack run plan    # 规划所有单元
terragrunt stack run apply   # 应用所有单元
terragrunt stack output      # 获取聚合输出
terragrunt stack clean       # 清理生成的目录

6. Generate Feature Flags (2025)

6. 生成Feature Flags(2025)

Runtime control without code changes.
Docs: Feature Flags Documentation Patterns:
references/common-patterns.md
→ Feature Flags Patterns
CRITICAL: Feature flag
default
values MUST be static (boolean, string, number). They CANNOT reference
local.*
values. Use static defaults and override via CLI/env vars.
Correct:
hcl
feature "enable_monitoring" {
  default = false  # Static value - OK
}
Incorrect:
hcl
feature "enable_monitoring" {
  default = local.env.locals.enable_monitoring  # Dynamic reference - FAILS
}
Usage:
bash
terragrunt apply --feature enable_monitoring=true
无需修改代码即可实现运行时控制。
文档Feature Flags文档 模式参考
references/common-patterns.md
→ Feature Flags模式
关键提示:Feature flag的
default
值必须是静态值(布尔值、字符串、数字)。 不能引用
local.*
值。使用静态默认值,通过CLI/环境变量覆盖。
正确示例:
hcl
feature "enable_monitoring" {
  default = false  # 静态值 - 合法
}
错误示例:
hcl
feature "enable_monitoring" {
  default = local.env.locals.enable_monitoring  # 动态引用 - 无效
}
使用方式:
bash
terragrunt apply --feature enable_monitoring=true

or

export TG_FEATURE="enable_monitoring=true"

**Environment-specific defaults:** Use different static defaults per environment file, not dynamic references.
export TG_FEATURE="enable_monitoring=true"

**特定环境默认值:** 为每个环境文件设置不同的静态默认值,而非使用动态引用。

7. Generate Exclude Blocks (2025)

7. 生成Exclude Blocks(2025)

Fine-grained execution control (replaces deprecated
skip
).
Docs: Exclude Block Reference Patterns:
references/common-patterns.md
→ Exclude Block Patterns
Actions:
"plan"
,
"apply"
,
"destroy"
,
"all"
,
"all_except_output"
Production Recommendation: For critical production resources, add exclude blocks to prevent accidental destruction:
hcl
undefined
细粒度执行控制(替代已弃用的
skip
)。
文档Exclude Block参考 模式参考
references/common-patterns.md
→ Exclude Block模式
操作类型
"plan"
,
"apply"
,
"destroy"
,
"all"
,
"all_except_output"
生产环境建议:对于关键生产资源,添加exclude块以防止意外销毁:
hcl
undefined

Protect production databases from accidental destroy

保护生产数据库不被意外销毁

exclude { if = true actions = ["destroy"] exclude_dependencies = false }
exclude { if = true actions = ["destroy"] exclude_dependencies = false }

Also use prevent_destroy for critical resources

同时为关键资源使用prevent_destroy

prevent_destroy = true
undefined
prevent_destroy = true
undefined

8. Generate Errors Blocks (2025)

8. 生成Errors Blocks(2025)

Advanced error handling (replaces deprecated
retryable_errors
).
Docs: Errors Block Reference Patterns:
references/common-patterns.md
→ Errors Block Patterns
高级错误处理(替代已弃用的
retryable_errors
)。
文档Errors Block参考 模式参考
references/common-patterns.md
→ Errors Block模式

9. Generate OpenTofu Engine Configuration (2025)

9. 处理自定义提供者/模块

Use OpenTofu as the IaC engine.
Docs: Engine Documentation Patterns:
references/common-patterns.md
→ OpenTofu Engine Patterns
生成包含自定义提供者的配置时:
  1. 确定提供者名称、源和版本
  2. 搜索:使用WebSearch搜索
    "[provider] terraform provider [version] documentation"
  3. 生成包含正确
    required_providers
    块的配置
  4. 在注释中记录认证要求

10. Handling Custom Providers/Modules

生成工作流

When generating configs with custom providers:
  1. Identify the provider name, source, and version
  2. Search using WebSearch:
    "[provider] terraform provider [version] documentation"
  3. Or use Context7 MCP if available for structured docs
  4. Generate with proper
    required_providers
    block
  5. Document authentication requirements in comments
关键提示:所有生成任务必须遵循此工作流。跳过步骤会导致验证错误。

Generation Workflow

步骤1:理解需求

CRITICAL: Follow this workflow for EVERY generation task. Skipping steps leads to validation errors.
  • 要生成哪种类型的配置?(根、子模块、独立模块、Stack)
  • 单环境还是多环境?
  • 模块之间存在哪些依赖关系?
  • 将使用哪些提供者/模块?

Step 1: Understand Requirements

步骤2:确定架构模式

  • What type of configuration? (root, child, standalone, stack)
  • Single or multi-environment?
  • What dependencies exist between modules?
  • What providers/modules will be used?
强制要求:在编写任何文件之前,选择并记录模式。
场景模式Root.hcl范围
多环境且共享根配置模式A与环境无关
单环境模式B感知环境
集中式环境变量模式C与环境无关
验证:
[ ] 已确定模式:____
[ ] Root.hcl将是:[ ] 与环境无关  [ ] 感知环境
[ ] env.hcl将放置在:____
[ ] 子模块将通过以下方式读取env.hcl:____

Step 2: Determine Architecture Pattern

步骤3:读取所需模板

MANDATORY: Select and document the pattern BEFORE writing any files.
ScenarioPatternRoot.hcl Scope
Multi-env with shared rootPattern AEnvironment-agnostic
Single environmentPattern BEnvironment-aware
Centralized env varsPattern CEnvironment-agnostic
Verify:
[ ] Pattern identified: ____
[ ] Root.hcl will be: [ ] environment-agnostic  [ ] environment-aware
[ ] env.hcl will be located in: ____
[ ] Child modules will read env.hcl via: ____
强制要求:在生成每种类型的配置之前,必须读取相关模板文件。
配置类型要读取的模板读取时机
根配置
assets/templates/root/terragrunt.hcl
生成任何root.hcl之前
子模块
assets/templates/child/terragrunt.hcl
生成任何子模块之前
独立模块
assets/templates/module/terragrunt.hcl
生成独立模块之前
Stack文件
assets/templates/stack/terragrunt.stack.hcl
生成Stack之前
同时读取:
  • references/common-patterns.md
    - 生成模式的主要来源

Step 3: Read Required Templates

步骤4:生成并验证

MANDATORY: Read the relevant template file(s) BEFORE generating each configuration type.
Configuration TypeTemplate to Read
Root configuration
assets/templates/root/terragrunt.hcl
Child module
assets/templates/child/terragrunt.hcl
Standalone module
assets/templates/module/terragrunt.hcl
Stack file
assets/templates/stack/terragrunt.stack.hcl
Catalog unit
assets/templates/catalog/terragrunt.hcl
Also read:
  • references/common-patterns.md
    - Primary source for generation patterns
验证策略:结合生成过程中的内联检查和最终的批量验证。
多环境项目的生成顺序:
  1. 先生成root.hcl
    • 生成过程中的内联检查:
      • 如果是与环境无关的根配置,不能使用
        read_terragrunt_config(find_in_parent_folders("env.hcl"))
      • remote_state
        块包含
        encrypt = true
      • 使用
        errors
        块(而非已弃用的
        retryable_errors
  2. 为每个环境生成env.hcl文件
    • 生成过程中的内联检查:
      • locals
        块包含environment、aws_region和模块特定变量
      • 没有引用该目录级别不存在的文件
  3. 生成子模块(如VPC等)- 先生成无依赖的模块
    • 生成过程中的内联检查:
      • include
        块使用
        find_in_parent_folders("root.hcl")
      • 包含
        read_terragrunt_config(find_in_parent_folders("env.hcl"))
  4. 生成依赖模块(如RDS、EKS等)
    • 生成过程中的内联检查:
      • dependency
        块包含
        mock_outputs
      • 生产环境模块包含
        prevent_destroy = true
        和/或
        exclude
  5. 所有文件生成完成后运行批量验证
    注意:完整的CLI验证需要所有文件都存在,因此这些操作在最后批量执行。
    bash
    # 批量验证命令(所有文件生成完成后运行):
    terragrunt hcl fmt --check          # 格式验证
    terragrunt dag graph                 # 依赖图验证

Step 4: Generate with Validation

步骤5:修复并重新验证

Validation Strategy: Use a combination of inline checks during generation and batch validation at the end.
Generation order for multi-environment projects:
  1. Generate root.hcl first
    • Inline checks (during generation):
      • No
        read_terragrunt_config(find_in_parent_folders("env.hcl"))
        if environment-agnostic
      • remote_state
        block has
        encrypt = true
      • errors
        block used (not deprecated
        retryable_errors
        )
  2. Generate env.hcl files for each environment
    • Inline checks (during generation):
      • locals
        block contains environment, aws_region, and module-specific vars
      • No references to files that don't exist at that directory level
  3. Generate child modules (VPC, etc.) - modules with NO dependencies first
    • Inline checks (during generation):
      • include
        block uses
        find_in_parent_folders("root.hcl")
      • read_terragrunt_config(find_in_parent_folders("env.hcl"))
        present
      • terraform.source
        uses valid syntax (tfr:///, git::, or relative path)
  4. Generate dependent modules (RDS, EKS, etc.)
    • Inline checks (during generation):
      • dependency
        blocks have
        mock_outputs
      • mock_outputs_allowed_terraform_commands
        includes
        ["validate", "plan", "destroy"]
      • Production modules have
        prevent_destroy = true
        and/or
        exclude
        block
  5. Run batch validation after ALL files are generated
    Note: Full CLI validation (
    terragrunt hcl fmt
    ,
    terragrunt dag graph
    ) requires all files to exist, so these are batched at the end.
    bash
    # Batch validation commands (run after all files exist):
    terragrunt hcl fmt --check          # Format validation
    terragrunt dag graph                 # Dependency graph validation
    • Invoke
      devops-skills:terragrunt-validator
      skill for comprehensive validation
如果验证失败:
  1. 分析错误(路径解析、缺失变量、语法错误)
  2. 在特定文件中修复问题
  3. 重新验证修复后的文件
  4. 重复直到所有错误都解决

Step 5: Fix and Re-Validate

步骤6:呈现结果

If validation fails:
  1. Analyze errors (path resolution, missing variables, syntax errors)
  2. Fix issues in the specific file(s)
  3. Re-validate the fixed file(s)
  4. Repeat until ALL errors are resolved
遵循以下"呈现要求"部分。

Step 6: Present Results

验证工作流

Follow "Presentation Requirements" section below.
关键提示:所有生成的配置必须经过验证。

Validation Workflow

增量验证检查

CRITICAL: Every generated configuration MUST be validated.
生成root.hcl后:
bash
cd <infrastructure-directory>
terragrunt hcl fmt --check
生成每个子模块后:
bash
cd <module-directory>
terragrunt hcl fmt --check

Incremental Validation Checks

如果模块无其他依赖:

After generating root.hcl:
bash
cd <infrastructure-directory>
terragrunt hcl fmt --check
After generating each child module:
bash
cd <module-directory>
terragrunt hcl fmt --check
terragrunt hcl validate --inputs
undefined

If no dependencies on other modules:

完整验证

terragrunt hcl validate --inputs
undefined
所有文件生成完成后:
  1. 调用验证技能:
    调用:devops-skills:terragrunt-validator技能
  2. 如果验证失败:
    • 分析错误(缺失占位符、无效语法、错误路径)
    • 修复问题
    • 重新验证(重复直到无错误)
  3. 如果验证成功: 呈现配置及使用说明
仅在以下情况跳过验证: 部分代码片段、文档示例或用户明确要求

Full Validation

呈现要求

After all files are generated:
  1. Invoke validation skill:
    Invoke: devops-skills:terragrunt-validator skill
  2. If validation fails:
    • Analyze errors (missing placeholders, invalid syntax, wrong paths)
    • Fix issues
    • Re-validate (repeat until ALL errors are resolved)
  3. If validation succeeds: Present configurations with usage instructions
Skip validation only for: Partial snippets, documentation examples, or explicit user request
强制要求:验证成功后,必须呈现以下所有部分。不完整的呈现是不被接受的。

Presentation Requirements

1. 目录结构摘要(强制要求)

MANDATORY: After successful validation, you MUST present ALL of the following sections. Incomplete presentation is not acceptable. Copy and fill in the templates below.
bash
undefined

1. Directory Structure Summary (MANDATORY)

显示生成的结构

bash
undefined
tree <infrastructure-directory>
undefined

Show the generated structure

2. 生成的文件(强制要求)

tree <infrastructure-directory>
undefined
输出包含所有生成文件的表格:
markdown
| 文件 | 用途 |
|------|---------|
| root.hcl | 所有子模块的共享配置(状态后端、提供者) |
| dev/env.hcl | 开发环境变量 |
| prod/env.hcl | 生产环境变量 |
| dev/vpc/terragrunt.hcl | 开发环境的VPC模块 |
| ... | ... |

2. Files Generated (MANDATORY)

3. 使用说明(强制要求)

Output this table with all generated files:
markdown
| File | Purpose |
|------|---------|
| root.hcl | Shared configuration for all child modules (state backend, provider) |
| dev/env.hcl | Development environment variables |
| prod/env.hcl | Production environment variables |
| dev/vpc/terragrunt.hcl | VPC module for development |
| ... | ... |
必须包含此部分。复制以下模板并填写实际值:
markdown
undefined

3. Usage Instructions (MANDATORY)

使用说明

前置条件

You MUST include this section. Copy the template below and fill in the actual values:
markdown
undefined
运行Terragrunt命令之前,请确保:
  1. 已配置AWS凭证(
    aws configure
    或环境变量)
  2. 用于状态存储的S3桶
    <BUCKET_NAME>
    已存在
  3. 用于状态锁定的DynamoDB表
    <TABLE_NAME>
    已存在

Usage Instructions

命令

Prerequisites

导航到基础设施目录

Before running Terragrunt commands, ensure:
  1. AWS credentials are configured (
    aws configure
    or environment variables)
  2. S3 bucket
    <BUCKET_NAME>
    exists for state storage
  3. DynamoDB table
    <TABLE_NAME>
    exists for state locking
cd <INFRASTRUCTURE_DIR>

Commands

初始化所有模块

Navigate to infrastructure directory

cd <INFRASTRUCTURE_DIR>
terragrunt run --all init

Initialize all modules

预览特定环境的变更

terragrunt run --all init
cd <ENV>/vpc && terragrunt plan

Preview changes for a specific environment

预览所有变更

cd <ENV>/vpc && terragrunt plan
terragrunt run --all plan

Preview all changes

应用变更(需要确认)

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

Apply changes (requires approval)

销毁(请极度谨慎使用)

terragrunt run --all apply
terragrunt run --all destroy
undefined

Destroy (use with extreme caution)

4. 特定环境说明(强制要求)

terragrunt run --all destroy
undefined
必须包含此部分。复制以下模板并填写实际值:
markdown
undefined

4. Environment-Specific Notes (MANDATORY)

环境说明

必需环境变量

You MUST include this section. Copy the template below and fill in the actual values:
markdown
undefined
变量描述
AWS_PROFILE要使用的AWS CLI配置文件
AWS_REGIONAWS区域(或在提供者中设置)

Environment Notes

前置条件

Required Environment Variables

VariableDescriptionExample
AWS_PROFILEAWS CLI profile to use
my-profile
AWS_REGIONAWS region (or set in provider)
us-east-1
  • S3桶
    <BUCKET_NAME>
    必须在首次运行前存在
  • 用于状态锁定的DynamoDB表
    <TABLE_NAME>
    必须存在
  • 用于Terraform状态管理的IAM权限

Prerequisites

生产环境特定保护

  • S3 bucket
    <BUCKET_NAME>
    must exist before first run
  • DynamoDB table
    <TABLE_NAME>
    must exist for state locking
  • IAM permissions for Terraform state management
模块保护措施描述
prod/rds
prevent_destroy = true
防止意外删除数据库
prod/rds
exclude { actions = ["destroy"] }
阻止销毁命令
undefined

Production-Specific Protections

5. 后续步骤(可选)

ModuleProtectionDescription
prod/rds
prevent_destroy = true
Prevents accidental database deletion
prod/rds
exclude { actions = ["destroy"] }
Blocks destroy commands
undefined
建议用户接下来可以执行的操作(添加更多模块、自定义配置等)

5. Next Steps (Optional)

最佳实践

Suggest what the user might want to do next (add more modules, customize configurations, etc.)
参考
../devops-skills:terragrunt-validator/references/best_practices.md
获取全面指南。
核心原则:
  • 使用
    include
    块继承根配置(遵循DRY原则)
  • 始终为依赖项提供模拟输出
  • 启用状态加密(
    encrypt = true
  • 永远不要硬编码凭证或密钥
  • 为临时错误配置重试逻辑
关于注册表模块的版本约束说明:使用Terraform注册表模块时,它们通常会定义自己的
required_providers
。在这种情况下,可以省略在
root.hcl
中生成
required_providers
以避免冲突。
需要避免的反模式:
  • 硬编码账户ID、区域或环境名称
  • 依赖项缺少模拟输出
  • 模块之间重复配置
  • 未加密的状态存储
  • Root.hcl尝试读取根目录下不存在的env.hcl

Best Practices

已弃用属性

Reference
../devops-skills:terragrunt-validator/references/best_practices.md
for comprehensive guidelines.
Key principles:
  • Use
    include
    blocks to inherit root configuration (DRY)
  • Always provide mock outputs for dependencies
  • Enable state encryption (
    encrypt = true
    )
  • Use
    generate
    blocks for provider configuration
  • Specify bounded version constraints (
    ~> 5.0
    , not
    >= 5.0
    ) for local/Git modules
  • Never hardcode credentials or secrets
  • Configure retry logic for transient errors
Note on Version Constraints with Registry Modules: When using Terraform Registry modules (e.g.,
tfr:///terraform-aws-modules/vpc/aws?version=5.1.0
), they typically define their own
required_providers
. In this case, you may omit generating
required_providers
in
root.hcl
to avoid conflicts. The module's pinned version (
?version=X.X.X
) provides the version constraint. See "Common Issues → Provider Conflict with Registry Modules" for details.
Anti-patterns to avoid:
  • Hardcoded account IDs, regions, or environment names
  • Missing mock outputs for dependencies
  • Duplicated configuration across modules
  • Unencrypted state storage
  • Missing or loose version constraints (except when using registry modules that define their own)
  • Root.hcl trying to read env.hcl that doesn't exist at root level
已弃用属性替代方案参考文档
skip
exclude
文档
retryable_errors
errors.retry
文档
run-all
run --all
迁移指南

Deprecated Attributes

资源

模板 - 生成前必须读取

DeprecatedReplacementReference
skip
exclude
block
Docs
retryable_errors
errors.retry
block
Docs
run-all
run --all
Migration
--terragrunt-*
flags
Unprefixed flagsCLI Reference
TERRAGRUNT_*
env vars
TG_*
env vars
CLI Reference
配置类型模板文件读取时机
根配置
assets/templates/root/terragrunt.hcl
生成任何root.hcl之前
子模块
assets/templates/child/terragrunt.hcl
生成任何子模块之前
独立模块
assets/templates/module/terragrunt.hcl
生成独立模块之前
Stack文件
assets/templates/stack/terragrunt.stack.hcl
生成Stack之前

Resources

参考文档

Templates - MUST Read Before Generating

Configuration TypeTemplate FileWhen to Read
Root configuration
assets/templates/root/terragrunt.hcl
Before generating any root.hcl
Child module
assets/templates/child/terragrunt.hcl
Before generating any child module
Standalone module
assets/templates/module/terragrunt.hcl
Before generating standalone modules
Stack file
assets/templates/stack/terragrunt.stack.hcl
Before generating stacks
Catalog unit
assets/templates/catalog/terragrunt.hcl
Before generating catalog units
参考文档内容读取时机
references/common-patterns.md
所有生成模式及示例生成前必须读取
../devops-skills:terragrunt-validator/references/best_practices.md
全面的最佳实践指南生成前必须读取

References

官方文档

ReferenceContentWhen to Read
references/common-patterns.md
All generation patterns with examplesAlways, before generating
../devops-skills:terragrunt-validator/references/best_practices.md
Comprehensive best practicesAlways, before generating

Official Documentation

常见问题

Root.hcl无法找到env.hcl

症状:
Error: Attempt to get attribute from null value
  on ./root.hcl line X:
原因: Root.hcl尝试通过
find_in_parent_folders("env.hcl")
读取
env.hcl
,但根目录下不存在env.hcl。
解决方案: 使root.hcl与环境无关:
hcl
undefined

Common Issues

多环境设置下,不要在root.hcl中执行此操作:

Root.hcl Cannot Find env.hcl

Symptom:
Error: Attempt to get attribute from null value
  on ./root.hcl line X:
  This value is null, so it does not have any attributes.
Cause: Root.hcl is trying to read
env.hcl
via
find_in_parent_folders("env.hcl")
, but env.hcl doesn't exist at the root level.
Solution: Make root.hcl environment-agnostic:
hcl
undefined
locals { env_vars = read_terragrunt_config(find_in_parent_folders("env.hcl")) # 失败 }

DON'T do this in root.hcl for multi-environment setups:

应该使用静态值或get_env():

locals { env_vars = read_terragrunt_config(find_in_parent_folders("env.hcl")) # FAILS }
generate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOF provider "aws" { region = "us-east-1" # 静态值,或使用get_env("AWS_REGION", "us-east-1") } EOF }
undefined

DO use static values or get_env():

子模块无法找到env.hcl

generate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOF provider "aws" { region = "us-east-1" # Static value, or use get_env("AWS_REGION", "us-east-1") } EOF }
undefined
症状:
Error: Attempt to get attribute from null value
  on ./dev/vpc/terragrunt.hcl line X:
原因: 子模块的
find_in_parent_folders("env.hcl")
无法找到env.hcl。
解决方案: 确保环境目录中存在env.hcl:
dev/
├── env.hcl           # 此文件必须存在
└── vpc/
    └── terragrunt.hcl  # 调用find_in_parent_folders("env.hcl")

Provider Conflict with Registry Modules

快速参考卡

文件读取检查清单

When using Terraform Registry modules (e.g.,
tfr:///terraform-aws-modules/vpc/aws
), they may define their own
required_providers
block. This can conflict with provider configuration generated by
root.hcl
.
Symptoms:
Error: Duplicate required providers configuration
Solutions:
  1. Remove conflicting generate block - If using registry modules that manage their own providers, avoid generating duplicate
    required_providers
    :
    hcl
    # In root.hcl - only generate provider config, not required_providers
    generate "provider" {
      path      = "provider.tf"
      if_exists = "overwrite_terragrunt"
      contents  = <<EOF
    provider "aws" {
      region = "us-east-1"
    }
    EOF
    }
  2. Use if_exists = "skip" - Skip generation if file already exists:
    hcl
    generate "versions" {
      path      = "versions.tf"
      if_exists = "skip"  # Don't overwrite module's versions.tf
      contents  = "..."
    }
  3. Clear cache - If conflicts persist after fixes:
    bash
    rm -rf .terragrunt-cache
    terragrunt init
生成前,按顺序读取以下文件:
  1. references/common-patterns.md
    - 了解可用模式
  2. ../devops-skills:terragrunt-validator/references/best_practices.md
    - 了解规则
  3. assets/templates/
    中的相关模板 - 结构参考

Feature Flag Validation Errors

架构决策树

If you see
Unknown variable; There is no variable named "local"
in feature blocks, ensure defaults are static values (see Feature Flags section above).
问题:是否有多个环境(开发/预发布/生产)?
├─ 是 → 问题:是否共享根配置?
│   ├─ 是 → 模式A:与环境无关的根配置
│   └─ 否  → 每个环境使用单独的root.hcl
└─ 否  → 问题:是否需要环境检测?
    ├─ 是 → 模式B:感知环境的根配置
    └─ 否  → 模式B:简单单环境

Child Module Cannot Find env.hcl

验证顺序

Symptom:
Error: Attempt to get attribute from null value
  on ./dev/vpc/terragrunt.hcl line X:
Cause: Child module's
find_in_parent_folders("env.hcl")
cannot find env.hcl.
Solution: Ensure env.hcl exists in the environment directory:
dev/
├── env.hcl           # This file MUST exist
└── vpc/
    └── terragrunt.hcl  # Calls find_in_parent_folders("env.hcl")
  1. 格式检查:
    terragrunt hcl fmt --check
  2. 输入验证:
    terragrunt hcl validate --inputs
  3. 全面验证:调用
    devops-skills:terragrunt-validator
    技能
  4. 修复错误 → 重新验证 → 重复直到无错误

Quick Reference Card

File Reading Checklist

Before generating, READ these files in order:
  1. references/common-patterns.md
    - Understand available patterns
  2. ../devops-skills:terragrunt-validator/references/best_practices.md
    - Know the rules
  3. Relevant template(s) from
    assets/templates/
    - Structural reference

Architecture Decision Tree

Q: Multiple environments (dev/staging/prod)?
├─ YES → Q: Shared root configuration?
│   ├─ YES → Pattern A: Environment-Agnostic Root
│   └─ NO  → Separate root.hcl per environment
└─ NO  → Q: Environment detection needed?
    ├─ YES → Pattern B: Environment-Aware Root
    └─ NO  → Pattern B: Simple single-environment

Validation Sequence

  1. Format check:
    terragrunt hcl fmt --check
  2. Input validation:
    terragrunt hcl validate --inputs
  3. Full validation: Invoke
    devops-skills:terragrunt-validator
    skill
  4. Fix errors → Re-validate → Repeat until clean