Terragrunt チートシート
インストール
| プラットフォーム | コマンド |
|---|
| macOS (Homebrew) | brew install terragrunt |
| Linux (Binary) | wget https://github.com/gruntwork-io/terragrunt/releases/download/v0.54.0/terragrunt_linux_amd64 && chmod +x terragrunt_linux_amd64 && sudo mv terragrunt_linux_amd64 /usr/local/bin/terragrunt |
| Windows (Chocolatey) | choco install terragrunt |
| Windows (Scoop) | scoop install terragrunt |
| Docker | docker pull alpine/terragrunt:latest |
| Version Manager (tgenv) | git clone https://github.com/cunymatthieu/tgenv.git ~/.tgenv && tgenv install latest |
| From Source (Go 1.21+) | git clone https://github.com/gruntwork-io/terragrunt.git && cd terragrunt && go install |
| Verify Installation | terragrunt --version |
基本コマンド
| コマンド | 説明 |
|---|
terragrunt init | バックエンド構成を自動的に管理された Terraform を初期化する |
terragrunt plan | インフラストラクチャの変更の実行計画を生成して表示する |
terragrunt apply | インフラストラクチャの変更を適用(確認プロンプトあり) |
terragrunt apply -auto-approve | 対話形式の確認なしに変更を適用 |
terragrunt destroy | すべての管理されたインフラストラクチャリソースを破棄する |
terragrunt destroy -auto-approve | 確認プロンプトなしでリソースを破棄 |
terragrunt validate | Terragruntとterraformの設定構文を検証する |
terragrunt fmt | Terraformの設定ファイルを標準的なスタイルにフォーマット |
terragrunt fmt -recursive | Recursively format all .tf files in subdirectories |
terragrunt output | ステートからすべての出力値を表示 |
terragrunt output <name> | Display specific output value (e.g., terragrunt output vpc_id) |
terragrunt output -json | 解析のために出力をJSONフォーマットで表示する |
terragrunt show | 人間が読める形式で現在の状態または保存された計画を表示 |
terragrunt console | 式をテストするための対話型コンソールを開く |
terragrunt refresh | 実際のインフラストラクチャーの状態でステートファイルを更新する |
terragrunt state list | ステート ファイルで追跡されているすべてのリソースを一覧表示 |
terragrunt state show <resource> | 特定のリソースの詳細な状態情報を表示 |
terragrunt workspace list | 利用可能なワークスペースをすべて一覧表示 |
terragrunt workspace select <name> | 指定されたワークスペースに切り替える |
terragrunt workspace new <name> | 新しいワークスペースを作成して切り替える |
高度な使用法
| コマンド | 説明 |
|---|
terragrunt run-all plan | 依存関係の順序で全モジュールにわたってプランを実行する |
terragrunt run-all apply | 依存関係を尊重しながら、すべてのモジュールに変更を適用する |
terragrunt run-all destroy | 逆依存関係の順序ですべてのモジュールを破棄する |
terragrunt run-all init | ディレクトリツリー内のすべてのモジュールを初期化する |
terragrunt run-all validate | すべてのモジュール設定を検証する |
terragrunt run-all output | すべてのモジュールからの出力を表示 |
terragrunt graph-dependencies | モジュール依存関係グラフを生成して表示する |
terragrunt render-json | 最終的な設定をJSONとしてレンダリングして検査する |
terragrunt hclfmt | Format terragrunt.hcl configuration files |
terragrunt state mv <source> <dest> | リソースを状態内の異なるアドレスに移動する |
terragrunt state rm <resource> | リソースを破壊せずに状態から削除する |
terragrunt import <address> <id> | 既存のインフラストラクチャを Terraform ステートにインポートする |
terragrunt taint <resource> | 次の適用時にレクリエーション用のリソースをマークする |
terragrunt untaint <resource> | リソースからタイント(taint)マーキングを削除する |
terragrunt plan -out=tfplan | 後で適用するために実行計画をファイルに保存 |
terragrunt apply tfplan | 以前に保存されたプラン ファイルを適用 |
terragrunt plan --terragrunt-log-level debug | 詳細なデバッグログを使用してプランを実行 |
terragrunt run-all apply --terragrunt-parallelism 3 | 並列モジュール実行を3つの同時操作に制限する |
terragrunt apply --terragrunt-source ../local-module | ローカル開発/テスト用のモジュールソースをオーバーライド |
terragrunt run-all apply --terragrunt-include-dir vpc | 特定のモジュールディレクトリでのみ実行 |
terragrunt run-all apply --terragrunt-exclude-dir legacy | 実行から特定のディレクトリを除外する |
terragrunt apply --terragrunt-include-external-dependencies | 実行に外部依存関係を含める |
terragrunt init -reconfigure | 既存の設定を無視してバックエンドを再構成する |
terragrunt init -upgrade | プロバイダプラグインを最新の許可されたバージョンにアップグレードする |
terragrunt state pull > terraform.tfstate | リモート状態をローカルにダウンロードして保存する |
設定
基本的な terragrunt.hcl の構造
# Include root configuration
include "root" {
path = find_in_parent_folders()
}
# Configure Terraform source
terraform {
source = "git::https://github.com/org/terraform-modules.git//vpc?ref=v1.0.0"
}
# Define inputs (variables)
inputs = {
environment = "production"
vpc_cidr = "10.0.0.0/16"
instance_type = "t3.medium"
}
リモート状態の設定 (ルート terragrunt.hcl)
# Configure remote state backend
remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
config = {
bucket = "my-terraform-state-${get_aws_account_id()}"
key = "${path_relative_to_include()}/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
依存関係の設定
# Define dependencies between modules
dependency "vpc" {
config_path = "../vpc"
# Mock outputs for validation without dependencies applied
mock_outputs = {
vpc_id = "vpc-temporary-id"
}
mock_outputs_allowed_terraform_commands = ["validate", "plan"]
}
# Use dependency outputs
inputs = {
vpc_id = dependency.vpc.outputs.vpc_id
subnet_ids = dependency.vpc.outputs.private_subnet_ids
}
プロバイダー設定の生成
# Auto-generate provider configuration
generate "provider" {
path = "provider.tf"
if_exists = "overwrite_terragrunt"
contents = <<EOF
provider "aws" {
region = "us-east-1"
default_tags {
tags = {
Environment = "${local.environment}"
ManagedBy = "Terragrunt"
}
}
}
EOF
}
ローカル変数と関数
# Define local variables
locals {
environment = "production"
region = "us-east-1"
# Parse environment from path
parsed_path = regex(".*/environments/(?P<env>.*?)/.*", get_terragrunt_dir())
env_name = local.parsed_path.env
# Common tags
common_tags = {
Environment = local.environment
ManagedBy = "Terragrunt"
Project = "MyProject"
}
}
# Use locals in inputs
inputs = merge(
local.common_tags,
{
region = local.region
}
)
フックの設定
# Execute commands before/after Terraform operations
terraform {
before_hook "before_init" {
commands = ["init"]
execute = ["echo", "Initializing Terraform..."]
}
after_hook "after_apply" {
commands = ["apply"]
execute = ["./scripts/notify-slack.sh"]
run_on_error = false
}
}
一般的なユースケース
ユースケース 1: マルチ環境インフラセットアップ
# Directory structure:
# └── environments/
# ├── terragrunt.hcl (root config)
# ├── dev/
# │ ├── vpc/terragrunt.hcl
# │ └── app/terragrunt.hcl
# └── prod/
# ├── vpc/terragrunt.hcl
# └── app/terragrunt.hcl
# Deploy entire dev environment
cd environments/dev
terragrunt run-all apply
# Deploy only VPC in production
cd environments/prod/vpc
terragrunt apply
# Plan all production changes
cd environments/prod
terragrunt run-all plan
ユースケース 2: モジュール依存関係の管理
# In app/terragrunt.hcl, reference VPC dependency:
# dependency "vpc" {
# config_path = "../vpc"
# }
# Apply app module (automatically applies VPC first if needed)
cd environments/dev/app
terragrunt apply --terragrunt-include-external-dependencies
# View dependency graph
cd environments/dev
terragrunt graph-dependencies | dot -Tpng > dependencies.png
ユースケース 3: ローカルモジュール開発
# Override module source to test local changes
cd environments/dev/vpc
terragrunt plan --terragrunt-source ../../../modules/vpc-local
# Apply with local module
terragrunt apply --terragrunt-source ../../../modules/vpc-local
# Reset to remote source
terragrunt plan --terragrunt-source-update
ユースケース 4: 状態管理と移行
# List all resources in state
terragrunt state list
# Move resource to new address
terragrunt state mv aws_instance.old aws_instance.new
# Import existing AWS resource
terragrunt import aws_instance.web i-1234567890abcdef0
# Remove resource from state (keeps actual resource)
terragrunt state rm aws_instance.temporary
# Pull remote state for inspection
terragrunt state pull > backup.tfstate
ユースケース 5: デバッグとトラブルシューティング
# Enable debug logging
export TERRAGRUNT_LOG_LEVEL=debug
terragrunt plan
# Run with trace-level logging
terragrunt apply --terragrunt-log-level trace 2>&1 | tee debug.log
# Validate all configurations
terragrunt run-all validate
# Check formatting issues
terragrunt hclfmt --terragrunt-check
# Test configuration rendering
terragrunt render-json | jq '.'
ベストプラクティス
- DRY原則を使用: バックエンド設定をルートに保持
terragrunt.hclし、重複を避けるためにincludeブロックを使用して子モジュールにインクルードする
- モジュールにバージョンを付ける: モジュールソースを常に特定のバージョンまたはタグに固定(例:
?ref=v1.0.0)して、再現可能なデプロイメントを確保する
- 依存関係管理を実装: 手動実行順序に頼るのではなく、
dependencyブロックを使用してモジュール間の関係を明示的に定義する
- ローカル変数と関数を活用: Terragruntの組み込み関数を使用
find_in_parent_folders(), get_aws_account_id(), and path_relative_to_include() for dynamic configuration
- Use mock outputs: Define
mock_outputs in dependency blocks to enable validation and planning without requiring all dependencies to be applied first
- Organize by environment: Structure directories by environment (dev/staging/prod) with shared configuration at the root level for consistency
- Enable state locking: Always configure DynamoDB tables for state locking when using S3 backend to prevent concurrent modification conflicts
- Use run-all carefully: Test with
run-all plan before run-all apply and consider using --terragrunt-parallelism to control concurrent executions
- Generate provider configs: Use
generate blocks to create provider configurations dynamically, ensuring consistency across modules
- Implement hooks for automation: Use
before_hook and after_hook to automate tasks like validation, notifications, or compliance checks
Troubleshooting
| 問題 | ソリューション |
|---|
| Error: “No Terraform configuration files” | Ensure terraform.source is correctly specified in terragrunt.hcl and the source path exists. Run terragrunt init to download modules. |
| Backend initialization fails | Check AWS credentials and permissions. Verify S3 bucket and DynamoDB table exist or set skip_bucket_creation = false in remote_state config. |
| Dependency outputs not found | Ensure dependency module is applied first. Use mock_outputs for planning without dependencies. Check config_path points to correct directory. |
| ”Working directory already exists” error | Clear Terragrunt cache: rm -rf .terragrunt-cache then run terragrunt init again. Or use --terragrunt-source-update flag. |
| Module source not updating | Force source update with terragrunt init --terragrunt-source-update or delete .terragrunt-cache directory to clear cached modules. |
| State lock acquisition timeout | 別のプロセスがロックを保持しています。DynamoDBテーブルでの完了を待つか、ロックを手動で解放してください。クラッシュしたプロセスを確認してください。 |
| “Module not found” with relative paths | Use find_in_parent_folders() to locate root config. Ensure relative paths account for Terragrunt’s working directory structure. |
| Run-all commands fail partially | Check individual module errors with --terragrunt-log-level debug. Verify dependencies are correctly defined. Use --terragrunt-ignore-dependency-errors cautiously. |
| Permission denied errors on AWS | Verify IAM role/user has required permissions. Check if role_arn in provider config is correct. Ensure MFA token is valid if required. |
| Circular dependency detected | Review dependency blocks to identify circular references. Restructure modules to break the cycle. Use terragrunt graph-dependencies to visualize. |
| Variables not being passed correctly | Check inputs block syntax in terragrunt.hcl. Verify variable names match module definitions. Use terragrunt render-json to inspect final config. |
| Performance issues with many modules | Adjust --terragrunt-parallelism to optimize concurrent executions. Consider splitting into smaller module groups. Use --terragrunt-include-dir for selective runs. |
| Terragruntコマンド | 同等の Terraform | 主な違い |
|---|
terragrunt init | terraform init | Auto-configures backend from terragrunt.hcl |
terragrunt plan | terraform plan | Terragrunt管理の入力と依存関係を含む |
terragrunt apply | terraform apply | 依存関係を処理し、設定を生成します |
terragrunt run-all apply | I apologize, but there is no text provided to translate. Could you please share the specific English text you would like me to translate to Japanese? | 依存関係の順序で複数のモジュールにわたって実行します |
terragrunt output | terraform output | 複数のモジュールからの出力を集約できる |