terragrunt-validator について
terragrunt-validatorは、Terragrunt設定を扱う担当者向けの検証・テストスキルです。フォーマット、構文、依存関係、プラン、セキュリティの確認をまとめ、Terragrunt 0.93以降のCLIに対応しています。
主な機能
- 01Terragrunt設定の一括検証
- 02HCL入力とフォーマットの確認
- 03tflintやTrivyなどの実行
- 04カスタムプロバイダーとモジュールの検出
- 05依存関係グラフとプランの検証
- 06Stacksと複数モジュールの操作
活用シーン
- 01インフラ設定の提出前チェック
- 02HCLや依存関係設定の問題調査
- 03インフラコードのセキュリティスキャン
MCP 対応
検出したカスタムプロバイダーやモジュールのドキュメント検索にContext7 MCPを使う方法が記載されています。このスキルがMCPサーバーを提供するとは説明されていません。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ akin-ozer/ cc-devops-skills --skill terragrunt-validatorインストール後、Claude Code で/terragrunt-validatorを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
.gitignorereferences/best_practices.mdscripts/detect_custom_resources.pyrun_ci_checks.shvalidate_terragrunt.shtest/test_detect_custom_resources.pytest_validate_terragrunt.shtest/infrastructure/common.hclroot.hcltest/infrastructure/dev/backend.tfenv.hclprovider.tfversions.tftest/infrastructure/dev/app/terragrunt.hcltest/infrastructure/dev/cache/terragrunt.hcltest/infrastructure/dev/database/terragrunt.hcltest/infrastructure/dev/monitoring/terragrunt.hcltest/infrastructure/dev/vpc/terragrunt.hcltest/infrastructure/prod/backend.tfenv.hclprovider.tfversions.tftest/infrastructure/prod/database/terragrunt.hcltest/infrastructure/prod/monitoring/terragrunt.hcltest/infrastructure/prod/vpc/terragrunt.hcltest/infrastructure/staging/backend.tfenv.hclprovider.tfversions.tftest/infrastructure/staging/vpc/terragrunt.hcl詳細
Terragrunt バリデーター
概要
このスキルでは、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 コードをベストプラクティスに照らしてリンティングする
- カスタムプロバイダーやモジュールを検出、調査する
- Terragrunt の設定に関する問題をデバッグする
- 依存関係グラフを確認する
- HCL ファイルをフォーマットする
- インフラストラクチャコードのセキュリティスキャンを実行する(Trivy、Checkov)
- 実行レポートとサマリーを生成する
Terragrunt のバージョン互換性
このスキルは、新しい CLI の再設計が含まれる Terragrunt 0.93+ 向けに設計されています。
CLI コマンドの移行リファレンス
| 非推奨のコマンド | 新しいコマンド |
|---|---|
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 |
0.93+ での主な変更点:
- 複数モジュールの操作では、
terragrunt run --allがterragrunt run-allに置き換わります - 依存関係の可視化では、
terragrunt dag graphがterragrunt graph-dependenciesに置き換わります - 入力値の検証では、
terragrunt hcl validate --inputsがvalidate-inputsに置き換わります - HCL 構文の検証には、
terragrunt hcl fmt --checkまたはterragrunt hcl validateを使用します - 完全な検証には、
terragrunt init && terragrunt validateが必要です
古いバージョンの Terragrunt を使用している場合、一部のコマンドの調整が必要になることがあります。
主な機能
1. 包括的な検証スイート
包括的な検証スクリプトを実行すると、すべてのチェックを一度に実行できます。
bash scripts/validate_terragrunt.sh [TARGET_DIR]
検証項目:
- HCL のフォーマット(
terragrunt hcl fmt --check) - HCL 入力値の検証(
terragrunt hcl validate --inputs) - Terragrunt 設定の構文
- Terraform 設定の検証
- tflint によるリンティング
- Trivy(または従来の tfsec)によるセキュリティスキャン
- 依存関係グラフの検証
- ドライラン計画
環境変数:
SKIP_PLAN=true- terragrunt plan の手順をスキップしますSKIP_SECURITY=true- セキュリティスキャン(Trivy/tfsec)をスキップしますSKIP_LINT=true- tflint によるリンティングをスキップしますSKIP_INIT=true- 検証前のterragrunt initをスキップしますSKIP_BACKEND_INIT=true--backend=falseを指定して init を実行します(CI/オフライン環境で便利です)SOFT_FAIL_SECURITY=true- 失敗扱いにせず、セキュリティ検出結果を報告しますTG_STRICT_MODE=true- 厳格モードを有効にします(非推奨機能がある場合はエラーになります)
使用例:
# Full validation
bash scripts/validate_terragrunt.sh ./infrastructure/prod
# Skip plan generation (faster)
SKIP_PLAN=true bash scripts/validate_terragrunt.sh ./infrastructure
# Only validate, skip linting and security
SKIP_LINT=true SKIP_SECURITY=true bash scripts/validate_terragrunt.sh
2. カスタムプロバイダーとモジュールの検出
検出スクリプトを使用して、ドキュメントを調べる必要があるカスタムプロバイダーとモジュールを特定します。
python3 scripts/detect_custom_resources.py [DIRECTORY] [--format text|json]
検出対象:
- カスタム Terraform プロバイダー(HashiCorp 以外)
- リモートモジュール(Git、Terraform Registry、HTTP)
- プロバイダーのバージョン
- モジュールのバージョンとソース
出力形式:
text- 検索の推奨事項を含む、人が読みやすいレポートjson- 自動化向けの機械可読形式
カスタムリソースが検出された場合:
重大:検出されたカスタムリソース(プロバイダーとモジュールの両方)すべてについて、必ずドキュメントを調べてください。1つも省略しないでください。これは必須であり、任意ではありません。
-
カスタムプロバイダーの場合:
- オプション A - WebSearch: プロバイダーのドキュメントを検索します
- クエリ形式:
"{provider_source} terraform provider documentation version {version}" - 例:
"mongodb/mongodbatlas terraform provider documentation version 1.14.0"
- クエリ形式:
- オプション B - Context7 MCP(推奨): Context7 を使用して構造化されたドキュメント検索を行います
- ステップ 1:プロバイダー名(例:「datadog terraform provider」)を指定して、
mcp__context7__resolve-library-idでライブラリ ID を解決します - ステップ 2:必須 - 解決したライブラリ ID を使い、
mcp__context7__query-docsでドキュメントを取得します "authentication requirements"や"configuration examples"のようなクエリを使用します
- ステップ 1:プロバイダー名(例:「datadog terraform provider」)を指定して、
- オプション A - WebSearch: プロバイダーのドキュメントを検索します
-
カスタムモジュールの場合(同様に重要です。省略しないでください):
- Terraform Registry のモジュール:
- Context7 を使用し、モジュール名(例:「terraform-aws-modules vpc」)を指定して
mcp__context7__resolve-library-idを実行します - 次に、
mcp__context7__query-docsでドキュメントを取得します - または、
https://registry.terraform.io/modules/{source}/{version}にアクセスします
- Context7 を使用し、モジュール名(例:「terraform-aws-modules vpc」)を指定して
- Git モジュール: リポジトリ URL を使って WebSearch で README またはドキュメントを検索します
- HTTP モジュール: ソース URL を調べてドキュメントを確認します
- お使いの Terraform/Terragrunt バージョンとの互換性に注意します
- Terraform Registry のモジュール:
-
ドキュメント検索のワークフロー(検出されたすべてのリソースで必須):
a) Run detect_custom_resources.py b) For EACH custom provider/module: - Note the exact version - Use Context7 MCP: 1. mcp__context7__resolve-library-id with libraryName: "{provider/module name}" 2. mcp__context7__query-docs with: - libraryId: "{resolved ID}" - query: "authentication requirements" (for auth requirements) 3. mcp__context7__query-docs with: - libraryId: "{resolved ID}" - query: "configuration examples" (for setup requirements) - OR use WebSearch with version-specific queries - Review documentation for: * Required configuration blocks * Authentication requirements (API keys, credentials) * Available resources/data sources * Known issues or breaking changes in the version c) Apply learnings to validation/troubleshooting d) Document findings if issues are encountered
Context7 MCP を使った例:
# 1. Detect custom resources
python3 scripts/detect_custom_resources.py ./infrastructure
# Output: Provider: datadog/datadog, Version: 3.30.0
# 2. Resolve library ID
mcp__context7__resolve-library-id with libraryName: "datadog terraform provider"
# Result: /datadog/terraform-provider-datadog
# 3. Fetch authentication docs (REQUIRED)
mcp__context7__query-docs with:
libraryId: "/datadog/terraform-provider-datadog"
query: "authentication requirements"
# 4. Fetch configuration docs
mcp__context7__query-docs with:
libraryId: "/datadog/terraform-provider-datadog"
query: "configuration examples"
WebSearch を使った例:
# Detect custom resources
python3 scripts/detect_custom_resources.py ./infrastructure
# Then search for documentation:
# WebSearch: "datadog terraform provider 3.30.0 authentication configuration"
# WebSearch: "datadog terraform provider api_key app_key setup"
3. ステップごとの検証
手動または細かく分けて検証する場合は、以下の個別コマンドを使用します。
フォーマットの検証
cd <target-directory>
terragrunt hcl fmt --check
# To auto-fix formatting
terragrunt hcl fmt
構成の検証
# Check HCL syntax and formatting
terragrunt hcl fmt --check
# Note: In Terragrunt 0.93+, for deeper configuration validation,
# initialize and validate (requires actual resources/credentials):
# terragrunt init && terragrunt validate
Terraform の検証
# Initialize if needed
terragrunt init
# Validate
terragrunt validate
tflint によるリンティング
# Initialize tflint (if .tflint.hcl exists)
tflint --init
# Run linting
tflint --recursive
Trivy によるセキュリティスキャン(推奨)
注: tfsec は Trivy に統合されており、現在は積極的にメンテナンスされていません。 新しいプロジェクトではすべて Trivy を使用してください。
# Using Trivy (recommended)
trivy config . --severity HIGH,CRITICAL
# With tfvars file
trivy config --tf-vars terraform.tfvars .
# Exclude downloaded modules
trivy config --tf-exclude-downloaded-modules .
# Legacy: Using tfsec (deprecated)
tfsec . --soft-fail
代替手段:Checkov によるセキュリティスキャン
# Scan directory
checkov -d . --framework terraform
# Scan with specific checks
checkov -d . --check CKV_AWS_21
# Output as JSON
checkov -d . --output json
依存関係グラフの検証
# Note: graph-dependencies command replaced with 'dag graph' in Terragrunt 0.93+
# Validate and display dependency graph
terragrunt dag graph
# Visualize dependencies (requires graphviz)
terragrunt dag graph | dot -Tpng > dependencies.png
ドライラン計画
# Single module
terragrunt plan
# All modules (new syntax - Terragrunt 0.93+)
terragrunt run --all plan
# Legacy syntax (deprecated)
# terragrunt run-all plan
4. 複数モジュールの操作
複数の Terragrunt モジュールを含むプロジェクトでは、run-all(非推奨)に代わり run --all を使用します。
# Validate all modules
terragrunt run --all validate
# Plan all modules
terragrunt run --all plan
# Apply all modules
terragrunt run --all apply
# Destroy all modules
terragrunt run --all destroy
# Format all HCL files
terragrunt hcl fmt
# With parallelism
terragrunt run --all plan --parallelism 4
# With strict mode (errors on deprecated features)
terragrunt --strict-mode run --all plan
# Or via environment variable
TG_STRICT_MODE=true terragrunt run --all plan
5. HCL 入力の検証(0.93+ で追加)
必須の入力がすべて設定され、未使用の入力がないことを検証します。
# Validate inputs
terragrunt hcl validate --inputs
# Show paths of invalid files
terragrunt hcl validate --show-config-path
# Combine with run --all to exclude invalid files
terragrunt run --all plan --queue-excludes-file <(terragrunt hcl validate --show-config-path || true)
6. 厳格モード
厳格モードを有効にして、非推奨の機能を早期に検出します。
# Via CLI flag
terragrunt --strict-mode run --all plan
# Via environment variable (recommended for CI/CD)
export TG_STRICT_MODE=true
terragrunt run --all plan
# Check available strict controls
terragrunt info strict
個別の厳格モード制御:
より細かく制御するには、--strict-control を使用して特定の制御を有効にします。
# Enable specific strict controls
terragrunt run --all plan --strict-control cli-redesign --strict-control deprecated-commands
# Via environment variable (comma-separated)
TG_STRICT_CONTROL='cli-redesign,deprecated-commands' terragrunt run --all plan
# Available strict controls:
# - cli-redesign: Errors on deprecated CLI syntax
# - deprecated-commands: Errors on deprecated commands (run-all, hclfmt, etc.)
# - root-terragrunt-hcl: Errors when using root terragrunt.hcl (use root.hcl instead)
# - skip-dependencies-inputs: Improves performance by not reading dependency inputs
# - bare-include: Errors on bare include blocks (use named includes)
7. 新しい CLI コマンド(0.93+)
構成のレンダリング
# Render configuration to JSON
terragrunt render --json
# Render and write to file
terragrunt render --json --write
# Output goes to terragrunt.rendered.json
情報の出力(terragrunt-info に代わるコマンド)
# Get contextual information about current configuration
terragrunt info print
# Output includes:
# - config_path
# - download_dir
# - terraform_binary
# - working_dir
ユニットの検索と一覧表示
# Find all units/stacks in directory
terragrunt find
# Output as JSON
terragrunt find --json
# Include dependency information
terragrunt find --json --dag
# List units (simpler output)
terragrunt list
実行の概要とレポート
# Run with summary output (default in newer versions)
terragrunt run --all plan
# Disable summary output
terragrunt run --all plan --summary-disable
# Generate detailed report file
terragrunt run --all plan --report-file=report.json
# CSV format report
terragrunt run --all plan --report-file=report.csv
8. Terragrunt スタック(v0.78.0+ で GA)
Terragrunt スタックは、terragrunt.stack.hcl ファイルを使用して宣言的にインフラストラクチャを生成します。
スタックファイルの構造
# terragrunt.stack.hcl
locals {
environment = "dev"
aws_region = "us-east-1"
}
# Define a unit (generates a single terragrunt.hcl)
unit "vpc" {
source = "git::[email protected]:acme/infra-catalog.git//units/vpc?ref=v0.0.1"
path = "vpc"
values = {
environment = local.environment
cidr = "10.0.0.0/16"
}
}
unit "database" {
source = "git::[email protected]:acme/infra-catalog.git//units/database?ref=v0.0.1"
path = "database"
values = {
environment = local.environment
vpc_path = "../vpc"
}
}
# Include reusable stacks
stack "monitoring" {
source = "git::[email protected]:acme/infra-catalog.git//stacks/monitoring?ref=v0.0.1"
path = "monitoring"
values = {
environment = local.environment
}
}
スタックコマンド
# Generate stack (creates .terragrunt-stack directory)
terragrunt stack generate
# Generate stack without validation
terragrunt stack generate --no-stack-validate
# Run command on all stack units
terragrunt stack run plan
terragrunt stack run apply
# Clean generated stack directories
terragrunt stack clean
# Get stack outputs
terragrunt stack output
スタックの検証制御
no_validation 属性を使用すると、特定のユニットの検証をスキップできます。
unit "experimental" {
source = "git::[email protected]:acme/infra-catalog.git//units/experimental?ref=v0.0.1"
path = "experimental"
# Skip validation for this unit (useful for incomplete/experimental units)
no_validation = true
values = {
environment = local.environment
}
}
スタックのメリット
- クリーンな作業ディレクトリ:生成されたコードは非表示の
.terragrunt-stackディレクトリに格納されます - 再利用可能なパターン:インフラストラクチャのパターンを一度定義すれば、何度でもデプロイできます
- バージョンの固定:環境ごとに異なるバージョンを固定できます
- アトミックな更新:モジュールと構成の両方を簡単にロールバックできます
9. Exec コマンド(任意のプログラムを実行)
exec コマンドを使用すると、Terragrunt のコンテキストでユニットに対して任意のプログラムを実行できます。tflint、checkov、AWS CLI などの他のツールを Terragrunt の設定と連携させる場合に便利です。
# Run tflint with unit context (TF_VAR_ env vars available)
terragrunt exec -- tflint
# Run checkov against specific unit
terragrunt exec -- checkov -d .
# Run AWS CLI with unit's configuration
terragrunt exec -- aws s3 ls s3://my-bucket
# Run custom scripts with Terragrunt context
terragrunt exec -- ./scripts/validate_terragrunt.sh
# Run across all units
terragrunt run --all exec -- tflint
主な機能:
- Terragrunt がユニットの入力値を読み込み、
TF_VAR_を接頭辞とする環境変数として利用できるようにします - 環境変数を使用できるあらゆるプログラムで動作します
- Terragrunt の認証コンテキスト(AWS プロファイルなど)と連携します
- マルチユニット操作で
run --allと組み合わせて使用できます
使用例:
- ユニットのコンテキストでセキュリティスキャナー(checkov、trivy)を実行する
- ユニットごとにリンター(tflint)を実行する
- 適切な認証情報を使って運用コマンド(AWS CLI)を実行する
- Terragrunt の入力値を必要とするカスタム検証スクリプトを実行する
10. フィーチャーフラグ(本番環境向け機能)
Terragrunt は、安全なインフラストラクチャの変更を実現するために、フィーチャーフラグを標準機能としてサポートしています。フィーチャーフラグを使うと、リスクを伴わずに未完成の作業を統合し、リリースとデプロイを切り離し、IaC の進化をコード化できます。
フィーチャーフラグの定義
# terragrunt.hcl
feature "enable_monitoring" {
default = false
}
feature "use_new_vpc" {
default = true
}
inputs = {
monitoring_enabled = feature.enable_monitoring.value
vpc_version = feature.use_new_vpc.value ? "v2" : "v1"
}
CLI でフィーチャーフラグを使用する
# Enable a feature flag
terragrunt plan --feature enable_monitoring=true
# Enable multiple feature flags
terragrunt plan --feature enable_monitoring=true --feature use_new_vpc=false
# Via environment variable
TG_FEATURE='enable_monitoring=true' terragrunt plan
run --all でフィーチャーフラグを使用する
# Apply feature flag across all units
terragrunt run --all plan --feature enable_monitoring=true
メリット:
- 安全な段階的展開:インフラストラクチャの一部で変更をテストできます
- 段階的な移行:新機能を段階的に有効化できます
- A/B テスト:インフラストラクチャの設定を比較できます
- 緊急時のロールバック:問題のある機能をすばやく無効化できます
11. 実験機能(オプトインの不安定な機能)
Terragrunt には、GA 前の不安定な機能を試すための実験機能システムがあります。
# Enable all experiments (not recommended for production)
terragrunt --experiment-mode run --all plan
# Enable specific experiment
terragrunt --experiment symlinks run --all plan
# Enable CAS (Content Addressable Storage) for faster cloning
terragrunt --experiment cas run --all plan
利用可能な実験機能:
symlinks- Terragrunt ユニットのシンボリックリンク解決をサポートしますcas- Git/モジュールのクローンを高速化するコンテンツアドレス可能ストレージfilter-flag- 高度なフィルタリング機能(1.0 で提供予定)
検証ワークフロー
Terragrunt の設定を検証する際は、次のワークフローに従ってください。
正式な実行可能ワークフロー(デフォルトのパス)
ドキュメントとスクリプトの整合性を保つため、実行可能なパスを 1 つ使用します。
# Main validation
bash scripts/validate_terragrunt.sh <target-directory>
# Deterministic fixture tests (required after script changes)
python3 test/test_detect_custom_resources.py
bash test/test_validate_terragrunt.sh
実行時の要件:
- フィクスチャテストは決定的である必要があります(合否の結果が安定していること)。
- 検証/セキュリティの失敗は、ゼロ以外の終了コードとして通知される必要があります。
ステップ 0:ベストプラクティスのリファレンスを読む(最初に必ず実施)
検証を開始する前に、ベストプラクティスのリファレンスファイルを必ず読んでください。これは必須です。
# Read the best practices reference file first
if [ -f references/best_practices.md ]; then
cat references/best_practices.md
else
echo "WARNING: references/best_practices.md not found; continue with built-in checklist below."
fi
これにより、検証するパターン、アンチパターン、チェックリストを把握できます。
初期評価
-
構造を把握する:
tree -L 3 <infrastructure-directory> -
Terragrunt ファイルを特定する:
find . -name "*.hcl" -o -name "terragrunt.hcl" -
カスタムリソースを検出する:
python3 scripts/detect_custom_resources.py .
ドキュメントの確認(検出されたすべてのカスタムリソースで必須)
重要:カスタムプロバイダーまたはモジュールが 1 つでも検出された場合は、それぞれのドキュメントを必ず確認してください。確認を省略しないでください。
-
検出されたカスタムプロバイダーごとに、ドキュメントを確認します:
- Context7 MCP を使用します(推奨):
- プロバイダー名を指定して
mcp__context7__resolve-library-idを実行します - クエリ「authentication requirements」を指定して
mcp__context7__query-docsを実行します - クエリ「configuration examples」を指定して
mcp__context7__query-docsを実行します
- プロバイダー名を指定して
- または、WebSearch を使用します:
"{provider} terraform provider {version} documentation"
- Context7 MCP を使用します(推奨):
-
検出されたカスタムモジュールごとに、ドキュメントを確認します:
- Terraform Registry のモジュールには Context7 MCP を使用します:
- モジュール名(例:「terraform-aws-modules vpc」)を指定して
mcp__context7__resolve-library-idを実行します - 関連する設定に関するクエリを指定して
mcp__context7__query-docsを実行します
- モジュール名(例:「terraform-aws-modules vpc」)を指定して
- Git モジュールの場合:リポジトリ URL を使って WebSearch を使用します
- HTTP モジュールの場合:ソース URL を調べてドキュメントを確認します
- Terraform Registry のモジュールには Context7 MCP を使用します:
-
各リソースについて、確認結果を記録します:
- 必須の設定ブロック
- 認証要件
- そのバージョンの既知の問題または破壊的変更
検証の実行
-
包括的な検証を実行します:
bash scripts/validate_terragrunt.sh <target-directory> -
出力にエラーがないか確認します:
- フォーマットエラー →
terragrunt hcl fmtで修正します - 設定エラー → terragrunt.hcl の構文と入力値を確認します
- Terraform の検証エラー → .tf ファイルまたは生成された設定を確認します
- リントの問題 → tflint の出力を確認して修正します
- セキュリティの問題 → Trivy/Checkov/tfsec の出力を確認して対処します
- 依存関係のエラー → dependency ブロックとパスを確認します
- plan のエラー → Terraform の設定とプロバイダーのセットアップを確認します
- フォーマットエラー →
ベストプラクティスの確認(必須 — すべてのチェックリストを完了する必要があります)
以下の各チェック項目を必ず検証し、結果(✅ 合格または ❌ 不合格)を記録してください。検証が不完全な場合は受け入れられません。
-
references/best_practices.mdを使用して、ベストプラクティスを明示的に検証します:設定パターンのチェックリスト — 各項目を検証します:
[ ] Include blocks: Child modules use `include "root" { path = find_in_parent_folders("root.hcl") }` [ ] Named includes: All include blocks have names (not bare `include {}`) [ ] Root file naming: Root config is named `root.hcl` (not `terragrunt.hcl`) [ ] Environment configs: Environment-level configs named `env.hcl` (not `terragrunt.hcl`) [ ] Common variables: Shared variables in `common.hcl` read via `read_terragrunt_config()`依存関係管理のチェックリスト:
[ ] Mock outputs: ALL dependency blocks have mock_outputs for validation [ ] Mock allowed commands: mock_outputs_allowed_terraform_commands includes ["validate", "plan", "init"] [ ] Explicit paths: Dependency config_path uses relative paths ("../vpc" not absolute) [ ] No circular deps: Run `terragrunt dag graph` to verify no cyclesセキュリティのチェックリスト:
[ ] State encryption: remote_state config has `encrypt = true` [ ] State locking: DynamoDB table configured for S3 backend [ ] No hardcoded credentials: Search for patterns like "AKIA", "password =", account IDs [ ] Sensitive variables: Passwords/keys use `sensitive = true` in variable blocks [ ] IAM roles: Provider uses assume_role instead of static credentialsDRY 原則のチェックリスト:
[ ] Generate blocks: Provider and backend configs use `generate` blocks [ ] Version constraints: terragrunt_version_constraint and terraform_version_constraint set [ ] Reusable locals: Common values in shared files, not duplicated [ ] if_exists: Generate blocks use appropriate if_exists strategy実行する簡易 grep チェック:
# Check for hardcoded AWS account IDs grep -r "[0-9]\{12\}" --include="*.hcl" . | grep -v mock # Check for potential credentials grep -ri "password\s*=" --include="*.hcl" . grep -ri "api_key\s*=" --include="*.hcl" . # Check for dependencies without mock_outputs grep -l "dependency\s" --include="*.hcl" -r . | xargs grep -L "mock_outputs" # Check for terragrunt.hcl files in non-module directories (anti-pattern) find . -name "terragrunt.hcl" -not -path "*/.terragrunt-cache/*" | head -20
トラブルシューティング
- よくある問題と解決方法:
問題:モジュールが見つからない
rm -rf .terragrunt-cache
terragrunt init
問題:プロバイダーの認証エラー
- 生成されたファイルのプロバイダー設定を確認します
- 環境変数または認証情報を確認します
- WebSearch でプロバイダーのドキュメントを確認します
問題:依存関係のエラー
- 依存関係のパスが正しいことを確認します
- 検証用に mock_outputs が指定されていることを確認します
terragrunt dag graphで依存関係グラフを確認します
問題:状態のロックエラー
terragrunt force-unlock <LOCK_ID>
問題:S3 バックエンドの dynamodb_table 非推奨警告
- 最近の Terraform バージョンでは、S3 バックエンドの
dynamodb_tableが非推奨であるという警告が表示される場合があります。 - ワークフローとの互換性がある場合は、バックエンド設定で
use_lockfile = trueを使用してください。 dynamodb_tableは、レガシーとの互換性が必要な場合にのみ使用してください。
問題:プロバイダーまたはモジュールのパラメーターが不明
- カスタムリソースの検出を再実行します
- WebSearch で最新のドキュメントを検索します
- バージョンの互換性を確認します
問題:Generate ブロックの競合(ファイルがすでに存在する)
ERROR: The file path ./versions.tf already exists and was not generated by terragrunt.
Can not generate terraform file: ./versions.tf already exists
解決方法: Terragrunt の generate ブロックと競合する静的な .tf ファイルが存在する場合に発生します。次のいずれかを実行します:
- 競合する静的ファイル(
versions.tf、provider.tf、backend.tf)を削除します - または、generate ブロックで
if_exists = "skip"を使用して、既存のファイルを上書きしないようにします
# Remove conflicting files
rm -f versions.tf provider.tf backend.tf
rm -rf .terragrunt-cache
問題:ルートの terragrunt.hcl に関するアンチパターン警告
WARN: Using `terragrunt.hcl` as the root of Terragrunt configurations is an anti-pattern
解決方法: Terragrunt 0.93 以降では、ルート設定ファイルの名前を terragrunt.hcl ではなく root.hcl にする必要があります。ファイル名を変更します:
mv terragrunt.hcl root.hcl
# Update include blocks in child modules to reference root.hcl
ベストプラクティスの統合
詳細な推奨事項については、包括的なベストプラクティスガイドを参照してください:
# Read the best practices reference
if [ -f references/best_practices.md ]; then
cat references/best_practices.md
else
echo "WARNING: references/best_practices.md not found; continue with checklist in this document."
fi
確認すべき主なベストプラクティス:
- ✅ 共有設定には
includeを使用する - ✅ 依存関係に mock_outputs を指定する
- ✅ プロバイダー設定には
generateブロックを使用する - ✅ 状態の暗号化とロックを有効にする
- ✅ 動的な値には環境変数を使用する
- ✅ バージョン制約を指定する
- ✅ 値のハードコードを避ける
- ✅ 意味のあるディレクトリ構成を使用する
- ✅ セキュリティ機能(暗号化、IAM ロール)を有効にする
検証時には、アンチパターンがないか確認してください:
- ❌ 認証情報やアカウント ID のハードコード
- ❌ mock outputs の不足
- ❌ ディレクトリ階層が深すぎる
- ❌ モジュール間での設定の重複
- ❌ バージョン制約の不足
- ❌ 暗号化されていない状態
具体例と詳細なガイダンスについては、references/best_practices.md を参照してください。
ツールの要件
必須:
- terragrunt(新しい CLI では 0.93.0 以降を推奨)
- terraform または opentofu(1.6.0 以降を推奨)
任意ですが、推奨:
- tflint - HCL のリント
- trivy - セキュリティスキャン(tfsec の後継)
- checkov - 代替のセキュリティスキャナー(750 以上の組み込みポリシー)
- graphviz(dot) - 依存関係の可視化
- jq - JSON の解析
- python3 - カスタムリソース検出スクリプト用
非推奨のツール:
- tfsec - Trivy に統合され、現在は積極的に保守されていません
インストールコマンド:
# macOS
brew install terragrunt terraform tflint trivy graphviz jq
# Install Trivy (recommended security scanner)
brew install trivy
# Install Checkov (alternative security scanner)
pip3 install checkov
# Legacy tfsec (deprecated - use trivy instead)
# brew install tfsec
# Linux - Trivy
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# Linux - Checkov
pip3 install checkov
# Verify installations
terragrunt --version
trivy --version
checkov --version
Context7 MCP との統合
Context7 MCP が利用可能な場合は、プロバイダーやモジュールのドキュメントを検索するために使用します。
-
ライブラリ ID を解決する:
mcp__context7__resolve-library-id with libraryName: "mongodb/mongodbatlas" -
ドキュメントを検索する:
mcp__context7__query-docs with libraryId: "/mongodb/mongodbatlas" and query: "authentication requirements"
これにより、WebSearch の代わりに、バージョンを考慮したドキュメントを直接取得できます。
自動化されたワークフロー
CI/CD との統合
決定論的なスキルレベルの CI ゲートを、ブロッキングチェックとして使用します。
bash scripts/run_ci_checks.sh --require-shellcheck
このゲートでは、次のチェックを実行します。
- シェル構文チェック(
bash -n) - Python 構文チェック(
python3 -m py_compile) - Python 回帰テスト(
test/test_detect_custom_resources.py) - シェル回帰テスト(
test/test_validate_terragrunt.sh) - ShellCheck のリント(
--require-shellcheckが設定されている場合、CI で必須)
このゲートを通過した後、Terragrunt/Terraform の認証情報が設定されたジョブで、環境に依存する検証を実行します。
#!/bin/bash
# ci-validate.sh
set -euo pipefail
echo "Running deterministic validator checks..."
bash scripts/run_ci_checks.sh --require-shellcheck
echo "Installing dependencies..."
# Install terragrunt, terraform, tflint, trivy/checkov
echo "Detecting custom resources..."
python3 scripts/detect_custom_resources.py . --format json > custom_resources.json
# Could integrate with automated documentation lookup here
echo "Running validation suite..."
SKIP_PLAN=true SKIP_BACKEND_INIT=true bash scripts/validate_terragrunt.sh .
echo "Validation complete!"
pre-commit フック
ローカル開発用の pre-commit フックの例:
#!/bin/bash
# .git/hooks/pre-commit
# Format check
terragrunt hcl fmt --check || {
echo "HCL formatting issues found. Run: terragrunt hcl fmt"
exit 1
}
# Quick HCL syntax validation (Terragrunt 0.93+)
# Note: For full validation, use: terragrunt init && terragrunt validate
# But that requires credentials. HCL format check catches syntax errors.
echo "Pre-commit validation passed!"
トラブルシューティングガイド
検証モードと終了時の動作
validate_terragrunt.sh は対象ディレクトリからモードを判定し、それに応じて Terragrunt コマンドの実行方法を変更します。
| モード | ディレクトリの構成 | Terragrunt HCL チェック | Terraform チェック | 終了時の動作 |
|---|---|---|---|---|
single | 対象ディレクトリに terragrunt.hcl(または terragrunt.stack.hcl)がある | terragrunt hcl validate | terragrunt validate(スキップされない限り terragrunt init を実行) | 構文エラーまたは検証失敗があると、ゼロ以外の値で終了 |
multi | 対象ディレクトリの下にネストされたユニットがある | terragrunt hcl validate --all(--all が未対応の場合は通常の hcl validate にフォールバック) | terragrunt run --all validate(スキップされない限り run --all init を実行) | いずれかのユニットで失敗すると、ゼロ以外の値で終了 |
root-only | root.hcl のみで、対象ディレクトリにユニットがない | 警告してスキップ | 警告してスキップ | これらのスキップされた手順では成功(0)を返す |
none | 認識可能な Terragrunt 設定ファイルがない | エラー | エラー | ゼロ以外の値を返す |
デバッグモード
トラブルシューティング用にデバッグ出力を有効にします。
# Terragrunt debug
TERRAGRUNT_DEBUG=1 terragrunt plan
# Terraform trace
TF_LOG=TRACE terragrunt plan
よくあるエラーパターン
「Error: Module not found」
- キャッシュをクリアします:
rm -rf .terragrunt-cache - 再初期化します:
terragrunt init
「Error: Provider not found」
- プロバイダーの設定を確認します
- カスタムリソースの検出を実行します
- WebSearch で正しいプロバイダーのソースとバージョンを調べます
- 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 以降)
- Terragrunt 0.93 以降には、後方互換性のない変更を含む新しい CLI があります
render-jsonやvalidate-inputsなどのコマンドは非推奨です- カスタムまたは未対応のコマンドには
terragrunt run -- <command>を使用します graph-dependenciesをdag graphに置き換えます- 参照先:https://terragrunt.gruntwork.io/docs/migrate/cli-redesign/
出力の解釈
成功を示す指標
✅ すべてのチェックに合格:
- すべての HCL ファイルが適切にフォーマットされている
- 入力値が有効である
- Terraform 設定が有効である
- リントの問題がない
- 重大なセキュリティ上の問題がない
- 依存関係グラフが有効である
- プランが正常に生成された
警告インジケーター
⚠️ 要確認:
- Trivy/Checkov/tfsec によるセキュリティ警告(重大ではありません)
- リントの提案(ベストプラクティス)
- 非推奨のプロバイダー機能
- 推奨される設定の不足
エラーインジケーター
✗ 修正必須:
- フォーマットエラー
- 無効な入力
- Terraform の検証失敗
- 循環依存
- プロバイダーの認証失敗
- 状態のロックエラー
高度な使用方法
カスタム検証ルール
.tflint.hcl を追加して、カスタムの tflint ルールを作成します。
plugin "terraform" {
enabled = true
preset = "recommended"
}
plugin "aws" {
enabled = true
version = "0.27.0"
source = "github.com/terraform-linters/tflint-ruleset-aws"
}
rule "terraform_naming_convention" {
enabled = true
}
カスタムセキュリティポリシー
.tfsec/config.yml を追加して、カスタムの tfsec ポリシーを作成します。
minimum_severity: MEDIUM
exclude:
- AWS001 # Example: exclude specific rules
依存関係グラフの分析
複雑な依存関係チェーンを分析します。
# Generate detailed graph (Terragrunt 0.93+ syntax)
terragrunt dag graph > graph.dot
# Convert to visual format
dot -Tpng graph.dot > graph.png
dot -Tsvg graph.dot > graph.svg
# Analyze for circular dependencies
grep -A5 "cycle" <(terragrunt dag graph 2>&1)
リソース
スクリプト
scripts/validate_terragrunt.sh- 包括的な検証スイートscripts/detect_custom_resources.py- カスタムプロバイダー/モジュール検出ツール
リファレンス
references/best_practices.md- 以下を網羅した包括的なベストプラクティスガイド:- ディレクトリ構造のパターン
- DRY 原則と設定の共有
- 依存関係の管理
- セキュリティのベストプラクティス
- テストと検証のワークフロー
- 避けるべき一般的なアンチパターン
- トラブルシューティングガイド
外部ドキュメント
完了条件
- ドキュメントとスクリプトで、標準の実行可能なワークフローが一致していること。
- 以下のコマンドでフィクスチャの実行が再現可能であること:
python3 test/test_detect_custom_resources.pybash test/test_validate_terragrunt.sh- 検証とセキュリティの失敗が、正しいゼロ以外の終了コードで報告されること。