terragrunt-generator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTerragrunt 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 (GA since v0.78.0)
terragrunt.stack.hcl - Feature Flags - Runtime control via blocks
feature - 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 - 基于的基础设施蓝图(自v0.78.0起正式可用)
terragrunt.stack.hcl - Feature Flags - 通过块实现运行时控制
feature - Exclude Blocks - 细粒度执行控制(替代已弃用的)
skip - Errors Blocks - 高级错误处理(替代已弃用的)
retryable_errors
Root Configuration Naming
根配置命名
| Approach | Root File | Include Syntax |
|---|---|---|
| Modern | | |
| Legacy | | |
| 方式 | 根文件 | 引用语法 |
|---|---|---|
| 现代方式 | | |
| 遗留方式 | | |
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: is environment-agnostic - it does NOT read environment-specific files.
root.hclinfrastructure/
├── 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.hclRoot.hcl constraints:
- ❌ CANNOT use - env.hcl doesn't exist at root level
read_terragrunt_config(find_in_parent_folders("env.hcl")) - ❌ CANNOT reference or
local.environmentthat come from env.hcllocal.aws_region - ✅ CAN use static values or for runtime configuration
get_env() - ✅ CAN use for state keys (this works dynamically)
${path_relative_to_include()}
Child modules read env.hcl:
hcl
undefined适用场景:管理多个环境(开发/预发布/生产)且共享根配置时。
核心原则:是与环境无关的——它不会读取特定环境的文件。
root.hclinfrastructure/
├── root.hcl # 与环境无关(无env.hcl引用)
├── dev/
│ ├── env.hcl # 环境变量(locals块)
│ ├── vpc/terragrunt.hcl
│ └── rds/terragrunt.hcl
└── prod/
├── env.hcl # 环境变量(locals块)
├── vpc/terragrunt.hcl
└── rds/terragrunt.hclRoot.hcl约束:
- ❌ 不能使用——根目录下不存在env.hcl
read_terragrunt_config(find_in_parent_folders("env.hcl")) - ❌ 不能引用来自env.hcl的或
local.environmentlocal.aws_region - ✅ 可以使用静态值或进行运行时配置
get_env() - ✅ 可以使用作为状态键(动态生效)
${path_relative_to_include()}
子模块读取env.hcl:
hcl
undefineddev/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/
}
undefinedinclude "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
}
undefinedPattern 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.hclRoot.hcl can detect environment:
hcl
undefined适用场景:单环境或所有环境共享同一根配置且需要检测环境时。
infrastructure/
├── root.hcl # 可通过get_env()或目录解析感知环境
├── account.hcl # 账户级配置(可选)
├── region.hcl # 区域级配置(可选)
└── vpc/
└── terragrunt.hclRoot.hcl可检测环境:
hcl
undefinedroot.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")
}
undefinedlocals {
从路径中解析环境(例如:"prod/vpc" -> "prod")
path_parts = split("/", path_relative_to_include())
environment = local.path_parts[0]
或使用环境变量
environment = get_env("TG_ENVIRONMENT", "dev")
}
undefinedPattern 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.hclenv.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.hclenv.hcl读取_env目录内容:
hcl
undefinedprod/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
}
undefinedlocals {
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
... 其他变量
}
undefinedPre-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强制要求:在编写任何文件之前,必须完成此检查清单并将其输出给用户,勾选已完成项。这是必填步骤。
在生成任何文件之前,输出已完成的检查清单:
undefinedArchitecture 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] 已验证:没有文件引用其所在位置不存在的路径
undefinedWhen 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 or with remote state, provider config, and common variables.
root.hclterragrunt.hclMANDATORY: Before generating, READ the template file:Read: assets/templates/root/terragrunt.hcl
Template:
Patterns: → Root Configuration Patterns
assets/templates/root/terragrunt.hclreferences/common-patterns.mdKey placeholders to replace:
- ,
[BUCKET_NAME],[AWS_REGION][DYNAMODB_TABLE] - ,
[TERRAFORM_VERSION],[PROVIDER_NAME][PROVIDER_VERSION] - ,
[ENVIRONMENT][PROJECT_NAME]
Root.hcl Design Principles:
- Environment-agnostic by default - Don't assume env.hcl exists at root level
- Use static values for provider/backend region - Or use for runtime config
get_env() - State key uses - This automatically includes environment path
path_relative_to_include() - Provider tags can be static - Environment-specific tags go in child modules
创建包含远程状态、提供者配置和通用变量的根级或。
root.hclterragrunt.hcl强制要求:生成前,必须读取模板文件:读取:assets/templates/root/terragrunt.hcl
模板:
模式参考: → 根配置模式
assets/templates/root/terragrunt.hclreferences/common-patterns.md需要替换的关键占位符:
- ,
[BUCKET_NAME],[AWS_REGION][DYNAMODB_TABLE] - ,
[TERRAFORM_VERSION],[PROVIDER_NAME][PROVIDER_VERSION] - ,
[ENVIRONMENT][PROJECT_NAME]
Root.hcl设计原则:
- 默认与环境无关 - 不要假设根目录下存在env.hcl
- 为提供者/后端区域使用静态值 - 或使用进行运行时配置
get_env() - 状态键使用- 自动包含环境路径
path_relative_to_include() - 提供者标签可以是静态的 - 特定环境的标签放在子模块中
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:
Patterns: → Child Module Patterns
assets/templates/child/terragrunt.hclreferences/common-patterns.mdModule 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.hclreferences/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.hcl4. Generate Multi-Environment Infrastructure
4. 生成多环境基础设施
Complete directory structures for dev/staging/prod.
MANDATORY: Before generating:
- Determine architecture pattern (see Architecture Patterns section)
- Read relevant templates for root and child modules
- Verify env.hcl placement and access patterns
Patterns: → Environment-Specific Patterns
references/common-patterns.mdTypical 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开发/预发布/生产环境的完整目录结构。
强制要求:生成前:
- 确定架构模式(请参阅架构模式部分)
- 读取根模块和子模块的相关模板
- 验证env.hcl的放置位置和访问模式
模式参考: → 特定环境模式
references/common-patterns.md典型结构(模式A - 与环境无关的根配置):
infrastructure/
├── root.hcl # 与环境无关的根配置
├── dev/
│ ├── env.hcl # 开发环境变量
│ └── vpc/terragrunt.hcl
└── prod/
├── env.hcl # 生产环境变量
└── vpc/terragrunt.hcl5. Generate Terragrunt Stacks (2025)
5. 生成Terragrunt Stacks(2025)
Infrastructure blueprints using .
terragrunt.stack.hclMANDATORY: Before generating, READ the template files:Read: assets/templates/stack/terragrunt.stack.hcl Read: assets/templates/catalog/terragrunt.hcl
Docs: Stacks Documentation
Template:
Catalog Template:
Patterns: → Stacks Patterns
assets/templates/stack/terragrunt.stack.hclassets/templates/catalog/terragrunt.hclreferences/common-patterns.mdCommands:
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文档
模板:
目录模板:
模式参考: → Stacks模式
assets/templates/stack/terragrunt.stack.hclassets/templates/catalog/terragrunt.hclreferences/common-patterns.md命令:
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: → Feature Flags Patterns
references/common-patterns.mdCRITICAL: Feature flagvalues MUST be static (boolean, string, number). They CANNOT referencedefaultvalues. Use static defaults and override via CLI/env vars.local.*
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文档
模式参考: → Feature Flags模式
references/common-patterns.md关键提示:Feature flag的值必须是静态值(布尔值、字符串、数字)。 不能引用default值。使用静态默认值,通过CLI/环境变量覆盖。local.*
正确示例:
hcl
feature "enable_monitoring" {
default = false # 静态值 - 合法
}错误示例:
hcl
feature "enable_monitoring" {
default = local.env.locals.enable_monitoring # 动态引用 - 无效
}使用方式:
bash
terragrunt apply --feature enable_monitoring=trueor
或
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 ).
skipDocs: Exclude Block Reference
Patterns: → Exclude Block Patterns
references/common-patterns.mdActions: , , , ,
"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参考
模式参考: → Exclude Block模式
references/common-patterns.md操作类型:, , , ,
"plan""apply""destroy""all""all_except_output"生产环境建议:对于关键生产资源,添加exclude块以防止意外销毁:
hcl
undefinedProtect 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
undefinedprevent_destroy = true
undefined8. Generate Errors Blocks (2025)
8. 生成Errors Blocks(2025)
Advanced error handling (replaces deprecated ).
retryable_errorsDocs: Errors Block Reference
Patterns: → Errors Block Patterns
references/common-patterns.md高级错误处理(替代已弃用的)。
retryable_errors文档:Errors Block参考
模式参考: → Errors Block模式
references/common-patterns.md9. Generate OpenTofu Engine Configuration (2025)
9. 处理自定义提供者/模块
Use OpenTofu as the IaC engine.
Docs: Engine Documentation
Patterns: → OpenTofu Engine Patterns
references/common-patterns.md生成包含自定义提供者的配置时:
- 确定提供者名称、源和版本
- 搜索:使用WebSearch搜索
"[provider] terraform provider [version] documentation" - 生成包含正确块的配置
required_providers - 在注释中记录认证要求
10. Handling Custom Providers/Modules
生成工作流
When generating configs with custom providers:
- Identify the provider name, source, and version
- Search using WebSearch:
"[provider] terraform provider [version] documentation" - Or use Context7 MCP if available for structured docs
- Generate with proper block
required_providers - 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.
| Scenario | Pattern | Root.hcl Scope |
|---|---|---|
| Multi-env with shared root | Pattern A | Environment-agnostic |
| Single environment | Pattern B | Environment-aware |
| Centralized env vars | Pattern C | Environment-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: ____强制要求:在生成每种类型的配置之前,必须读取相关模板文件。
| 配置类型 | 要读取的模板 | 读取时机 |
|---|---|---|
| 根配置 | | 生成任何root.hcl之前 |
| 子模块 | | 生成任何子模块之前 |
| 独立模块 | | 生成独立模块之前 |
| Stack文件 | | 生成Stack之前 |
同时读取:
- - 生成模式的主要来源
references/common-patterns.md
Step 3: Read Required Templates
步骤4:生成并验证
MANDATORY: Read the relevant template file(s) BEFORE generating each configuration type.
| Configuration Type | Template to Read |
|---|---|
| Root configuration | |
| Child module | |
| Standalone module | |
| Stack file | |
| Catalog unit | |
Also read:
- - Primary source for generation patterns
references/common-patterns.md
验证策略:结合生成过程中的内联检查和最终的批量验证。
多环境项目的生成顺序:
-
先生成root.hcl
- 生成过程中的内联检查:
- 如果是与环境无关的根配置,不能使用
read_terragrunt_config(find_in_parent_folders("env.hcl")) - 块包含
remote_stateencrypt = true - 使用块(而非已弃用的
errors)retryable_errors
- 如果是与环境无关的根配置,不能使用
- 生成过程中的内联检查:
-
为每个环境生成env.hcl文件
- 生成过程中的内联检查:
- 块包含environment、aws_region和模块特定变量
locals - 没有引用该目录级别不存在的文件
-
- 生成过程中的内联检查:
-
生成子模块(如VPC等)- 先生成无依赖的模块
- 生成过程中的内联检查:
- 块使用
includefind_in_parent_folders("root.hcl") - 包含
read_terragrunt_config(find_in_parent_folders("env.hcl"))
-
- 生成过程中的内联检查:
-
生成依赖模块(如RDS、EKS等)
- 生成过程中的内联检查:
- 块包含
dependencymock_outputs - 生产环境模块包含和/或
prevent_destroy = true块exclude
-
- 生成过程中的内联检查:
-
所有文件生成完成后运行批量验证注意:完整的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:
-
Generate root.hcl first
- Inline checks (during generation):
- No if environment-agnostic
read_terragrunt_config(find_in_parent_folders("env.hcl")) - block has
remote_stateencrypt = true - block used (not deprecated
errors)retryable_errors
- No
- Inline checks (during generation):
-
Generate env.hcl files for each environment
- Inline checks (during generation):
- block contains environment, aws_region, and module-specific vars
locals - No references to files that don't exist at that directory level
-
- Inline checks (during generation):
-
Generate child modules (VPC, etc.) - modules with NO dependencies first
- Inline checks (during generation):
- block uses
includefind_in_parent_folders("root.hcl") - present
read_terragrunt_config(find_in_parent_folders("env.hcl")) - uses valid syntax (tfr:///, git::, or relative path)
terraform.source
-
- Inline checks (during generation):
-
Generate dependent modules (RDS, EKS, etc.)
- Inline checks (during generation):
- blocks have
dependencymock_outputs - includes
mock_outputs_allowed_terraform_commands["validate", "plan", "destroy"] - Production modules have and/or
prevent_destroy = trueblockexclude
-
- Inline checks (during generation):
-
Run batch validation after ALL files are generatedNote: Full CLI validation (,
terragrunt hcl fmt) requires all files to exist, so these are batched at the end.terragrunt dag graphbash# Batch validation commands (run after all files exist): terragrunt hcl fmt --check # Format validation terragrunt dag graph # Dependency graph validation- Invoke skill for comprehensive validation
devops-skills:terragrunt-validator
- Invoke
如果验证失败:
- 分析错误(路径解析、缺失变量、语法错误)
- 在特定文件中修复问题
- 重新验证修复后的文件
- 重复直到所有错误都解决
Step 5: Fix and Re-Validate
步骤6:呈现结果
If validation fails:
- Analyze errors (path resolution, missing variables, syntax errors)
- Fix issues in the specific file(s)
- Re-validate the fixed file(s)
- 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 --checkIncremental Validation Checks
如果模块无其他依赖:
After generating root.hcl:
bash
cd <infrastructure-directory>
terragrunt hcl fmt --checkAfter generating each child module:
bash
cd <module-directory>
terragrunt hcl fmt --checkterragrunt hcl validate --inputs
undefinedIf no dependencies on other modules:
完整验证
terragrunt hcl validate --inputs
undefined所有文件生成完成后:
-
调用验证技能:
调用:devops-skills:terragrunt-validator技能 -
如果验证失败:
- 分析错误(缺失占位符、无效语法、错误路径)
- 修复问题
- 重新验证(重复直到无错误)
-
如果验证成功: 呈现配置及使用说明
仅在以下情况跳过验证: 部分代码片段、文档示例或用户明确要求
Full Validation
呈现要求
After all files are generated:
-
Invoke validation skill:
Invoke: devops-skills:terragrunt-validator skill -
If validation fails:
- Analyze errors (missing placeholders, invalid syntax, wrong paths)
- Fix issues
- Re-validate (repeat until ALL errors are resolved)
-
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
undefined1. Directory Structure Summary (MANDATORY)
显示生成的结构
bash
undefinedtree <infrastructure-directory>
undefinedShow 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
undefined3. Usage Instructions (MANDATORY)
使用说明
—
前置条件
You MUST include this section. Copy the template below and fill in the actual values:
markdown
undefined运行Terragrunt命令之前,请确保:
- 已配置AWS凭证(或环境变量)
aws configure - 用于状态存储的S3桶已存在
<BUCKET_NAME> - 用于状态锁定的DynamoDB表已存在
<TABLE_NAME>
Usage Instructions
命令
Prerequisites
导航到基础设施目录
Before running Terragrunt commands, ensure:
- AWS credentials are configured (or environment variables)
aws configure - S3 bucket exists for state storage
<BUCKET_NAME> - DynamoDB table exists for state locking
<TABLE_NAME>
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
undefinedDestroy (use with extreme caution)
4. 特定环境说明(强制要求)
terragrunt run --all destroy
undefined必须包含此部分。复制以下模板并填写实际值:
markdown
undefined4. 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_REGION | AWS区域(或在提供者中设置) |
Environment Notes
前置条件
Required Environment Variables
—
| Variable | Description | Example |
|---|---|---|
| AWS_PROFILE | AWS CLI profile to use | |
| AWS_REGION | AWS region (or set in provider) | |
- S3桶必须在首次运行前存在
<BUCKET_NAME> - 用于状态锁定的DynamoDB表必须存在
<TABLE_NAME> - 用于Terraform状态管理的IAM权限
Prerequisites
生产环境特定保护
- S3 bucket must exist before first run
<BUCKET_NAME> - DynamoDB table must exist for state locking
<TABLE_NAME> - IAM permissions for Terraform state management
| 模块 | 保护措施 | 描述 |
|---|---|---|
| prod/rds | | 防止意外删除数据库 |
| prod/rds | | 阻止销毁命令 |
undefinedProduction-Specific Protections
5. 后续步骤(可选)
| Module | Protection | Description |
|---|---|---|
| prod/rds | | Prevents accidental database deletion |
| prod/rds | | 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核心原则:
- 使用块继承根配置(遵循DRY原则)
include - 始终为依赖项提供模拟输出
- 启用状态加密()
encrypt = true - 永远不要硬编码凭证或密钥
- 为临时错误配置重试逻辑
关于注册表模块的版本约束说明:使用Terraform注册表模块时,它们通常会定义自己的。在这种情况下,可以省略在required_providers中生成root.hcl以避免冲突。required_providers
需要避免的反模式:
- 硬编码账户ID、区域或环境名称
- 依赖项缺少模拟输出
- 模块之间重复配置
- 未加密的状态存储
- Root.hcl尝试读取根目录下不存在的env.hcl
Best Practices
已弃用属性
Reference for comprehensive guidelines.
../devops-skills:terragrunt-validator/references/best_practices.mdKey principles:
- Use blocks to inherit root configuration (DRY)
include - Always provide mock outputs for dependencies
- Enable state encryption ()
encrypt = true - Use blocks for provider configuration
generate - Specify bounded version constraints (, not
~> 5.0) for local/Git modules>= 5.0 - 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.,), they typically define their owntfr:///terraform-aws-modules/vpc/aws?version=5.1.0. In this case, you may omit generatingrequired_providersinrequired_providersto avoid conflicts. The module's pinned version (root.hcl) provides the version constraint. See "Common Issues → Provider Conflict with Registry Modules" for details.?version=X.X.X
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
Deprecated Attributes
资源
—
模板 - 生成前必须读取
| Deprecated | Replacement | Reference |
|---|---|---|
| | Docs |
| | Docs |
| | Migration |
| Unprefixed flags | CLI Reference |
| | CLI Reference |
| 配置类型 | 模板文件 | 读取时机 |
|---|---|---|
| 根配置 | | 生成任何root.hcl之前 |
| 子模块 | | 生成任何子模块之前 |
| 独立模块 | | 生成独立模块之前 |
| Stack文件 | | 生成Stack之前 |
Resources
参考文档
Templates - MUST Read Before Generating
—
| Configuration Type | Template File | When to Read |
|---|---|---|
| Root configuration | | Before generating any root.hcl |
| Child module | | Before generating any child module |
| Standalone module | | Before generating standalone modules |
| Stack file | | Before generating stacks |
| Catalog unit | | Before generating catalog units |
| 参考文档 | 内容 | 读取时机 |
|---|---|---|
| 所有生成模式及示例 | 生成前必须读取 |
| 全面的最佳实践指南 | 生成前必须读取 |
References
官方文档
| Reference | Content | When to Read |
|---|---|---|
| All generation patterns with examples | Always, before generating |
| Comprehensive best practices | Always, before generating |
Official Documentation
常见问题
—
Root.hcl无法找到env.hcl
症状:
Error: Attempt to get attribute from null value
on ./root.hcl line X:原因: Root.hcl尝试通过读取,但根目录下不存在env.hcl。
find_in_parent_folders("env.hcl")env.hcl解决方案: 使root.hcl与环境无关:
hcl
undefinedCommon 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 via , but env.hcl doesn't exist at the root level.
env.hclfind_in_parent_folders("env.hcl")Solution: Make root.hcl environment-agnostic:
hcl
undefinedlocals {
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
}
undefinedDO 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:原因: 子模块的无法找到env.hcl。
find_in_parent_folders("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., ), they may define their own block. This can conflict with provider configuration generated by .
tfr:///terraform-aws-modules/vpc/awsrequired_providersroot.hclSymptoms:
Error: Duplicate required providers configurationSolutions:
-
Remove conflicting generate block - If using registry modules that manage their own providers, avoid generating duplicate:
required_providershcl# 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 } -
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 = "..." } -
Clear cache - If conflicts persist after fixes:bash
rm -rf .terragrunt-cache terragrunt init
生成前,按顺序读取以下文件:
- - 了解可用模式
references/common-patterns.md - - 了解规则
../devops-skills:terragrunt-validator/references/best_practices.md - 中的相关模板 - 结构参考
assets/templates/
Feature Flag Validation Errors
架构决策树
If you see in feature blocks, ensure defaults are static values (see Feature Flags section above).
Unknown variable; There is no variable named "local"问题:是否有多个环境(开发/预发布/生产)?
├─ 是 → 问题:是否共享根配置?
│ ├─ 是 → 模式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 cannot find env.hcl.
find_in_parent_folders("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")- 格式检查:
terragrunt hcl fmt --check - 输入验证:
terragrunt hcl validate --inputs - 全面验证:调用技能
devops-skills:terragrunt-validator - 修复错误 → 重新验证 → 重复直到无错误
Quick Reference Card
—
File Reading Checklist
—
Before generating, READ these files in order:
- - Understand available patterns
references/common-patterns.md - - Know the rules
../devops-skills:terragrunt-validator/references/best_practices.md - Relevant template(s) from - Structural reference
assets/templates/
—
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
—
- Format check:
terragrunt hcl fmt --check - Input validation:
terragrunt hcl validate --inputs - Full validation: Invoke skill
devops-skills:terragrunt-validator - Fix errors → Re-validate → Repeat until clean
—