_
_
_
Terragrunt Cheatsheet¶
• Installation
| Platform | Command |
|---|---|
| macOS (Homebrew) | INLINE_CODE_11 |
| Linux (Binary) | INLINE_CODE_12 |
| Windows (Chocolatey) | INLINE_CODE_13 |
| Windows (Scoop) | INLINE_CODE_14 |
| Docker | INLINE_CODE_15 |
| Version Manager (tgenv) | INLINE_CODE_16 |
| From Source (Go 1.21+) | INLINE_CODE_17 |
| Verify Installation | INLINE_CODE_18 |
oder Grundlegende Befehle
| Command | Description |
|---|---|
| INLINE_CODE_19 | Initialize Terraform with backend configuration automatically managed |
| INLINE_CODE_20 | Generate and show execution plan for infrastructure changes |
| INLINE_CODE_21 | Apply infrastructure changes (prompts for confirmation) |
| INLINE_CODE_22 | Apply changes without interactive confirmation |
| INLINE_CODE_23 | Destroy all managed infrastructure resources |
| INLINE_CODE_24 | Destroy resources without confirmation prompt |
| INLINE_CODE_25 | Validate Terragrunt and Terraform configuration syntax |
| INLINE_CODE_26 | Format Terraform configuration files to canonical style |
| INLINE_CODE_27 | Recursively format all INLINE_CODE_28 files in subdirectories |
| INLINE_CODE_29 | Display all output values from the state |
| INLINE_CODE_30 | Display specific output value (e.g., INLINE_CODE_31) |
| INLINE_CODE_32 | Display outputs in JSON format for parsing |
| INLINE_CODE_33 | Display current state or saved plan in human-readable format |
| INLINE_CODE_34 | Open interactive console for testing expressions |
| INLINE_CODE_35 | Update state file with real infrastructure status |
| INLINE_CODE_36 | List all resources tracked in the state file |
| INLINE_CODE_37 | Show detailed state information for specific resource |
| INLINE_CODE_38 | List all available workspaces |
| INLINE_CODE_39 | Switch to specified workspace |
| INLINE_CODE_40 | Create and switch to new workspace |
| _ | |
| / Fortgeschrittene Nutzung |
| Command | Description |
|---|---|
| INLINE_CODE_41 | Execute plan across all modules in dependency order |
| INLINE_CODE_42 | Apply changes to all modules respecting dependencies |
| INLINE_CODE_43 | Destroy all modules in reverse dependency order |
| INLINE_CODE_44 | Initialize all modules in the directory tree |
| INLINE_CODE_45 | Validate all module configurations |
| INLINE_CODE_46 | Display outputs from all modules |
| INLINE_CODE_47 | Generate and display module dependency graph |
| INLINE_CODE_48 | Render final configuration as JSON for inspection |
| INLINE_CODE_49 | Format INLINE_CODE_50 configuration files |
| INLINE_CODE_51 | Move resource to different address in state |
| INLINE_CODE_52 | Remove resource from state without destroying it |
| INLINE_CODE_53 | Import existing infrastructure into Terraform state |
| INLINE_CODE_54 | Mark resource for recreation on next apply |
| INLINE_CODE_55 | Remove taint marking from resource |
| INLINE_CODE_56 | Save execution plan to file for later apply |
| INLINE_CODE_57 | Apply previously saved plan file |
| INLINE_CODE_58 | Run plan with detailed debug logging |
| INLINE_CODE_59 | Limit parallel module execution to 3 concurrent operations |
| INLINE_CODE_60 | Override module source for local development/testing |
| INLINE_CODE_61 | Execute only on specific module directories |
| INLINE_CODE_62 | Exclude specific directories from execution |
| INLINE_CODE_63 | Include external dependencies in execution |
| INLINE_CODE_64 | Reconfigure backend, ignoring existing configuration |
| INLINE_CODE_65 | Upgrade provider plugins to latest allowed versions |
| INLINE_CODE_66 | Download and save remote state locally |
| _ | |
| Konfiguration |
Basic terragrunt.hcl Struktur¶
# 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"
}
Remote State Configuration (Root 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"
}
}
Dependency Configuration¶
# 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
}
Provider-Konfiguration generieren¶
# 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
}
Lokale und Funktionen¶
# 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
}
)
Hooks Konfiguration¶
# 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
}
}
Häufige Anwendungsfälle
Use Case 1: Multi-Environment Infrastructure Setup¶
# 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
Use Case 2: Modulabhängigkeiten verwalten¶
# 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
Use Case 3: Local Module Development¶
# 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
Use Case 4: State Management und Migration¶
# 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
Use Case 5: Debugging und Fehlerbehebung¶
# 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 '.'
oder Best Practices
- ** Verwenden Sie DRY-Prinzip*: Halten Sie Backend-Konfiguration in root
terragrunt.hclund schließen Sie es in Kindermodulen mitincludeBlöcke ein, um Doppelarbeit zu vermeiden - Version Ihrer Module: Pin-Modulquellen immer auf bestimmte Versionen oder Tags (z.B.
?ref=v1.0.0_), um reproduzierbare Bereitstellungen zu gewährleisten - Umsetzungsmanagement: Verwenden Sie
dependencyBlöcke, um die Beziehungen zwischen Modulen explizit zu definieren, anstatt auf manuelle Ausführungsreihenfolge zu verlassen - ** Lokale und Funktionen verwalten*: Verwenden Sie Terragrunts eingebaute Funktionen wie
find_in_parent_folders(),get_aws_account_id()undpath_relative_to_include()für dynamische Konfiguration - **Benutze Mock-Ausgänge*: Define
mock_outputsin Abhängigkeitsblöcken, um Validierung und Planung zu ermöglichen, ohne dass alle Abhängigkeiten zuerst angewendet werden müssen - **Organisieren nach Umwelt*: Strukturverzeichnisse nach Umwelt (dev/staging/prod) mit gemeinsamer Konfiguration auf Wurzelebene für Konsistenz
- ** Zustandssicherung**: Konfigurieren Sie immer DynamoDB-Tabellen für die Zustandssicherung, wenn Sie S3 Backend verwenden, um gleichzeitige Modifikationskonflikte zu verhindern
- Use run-all aufmerksam: Testen Sie mit
run-all planvorrun-all apply_ und prüfen Sie mit--terragrunt-parallelismzur Steuerung von gleichzeitigen Ausführungen - **Generate Provider configs*: Verwenden Sie
generateBlöcke, um Anbieterkonfigurationen dynamisch zu erstellen und Konsistenzen über Module zu gewährleisten - **Implementieren Sie Haken für die Automatisierung*: Verwenden Sie
before_hookundafter_hook, um Aufgaben wie Validierung, Benachrichtigungen oder Compliance-Checks zu automatisieren
Fehlerbehebung
| Issue | Solution |
|---|---|
| Error: "No Terraform configuration files" | Ensure INLINE_CODE_81 is correctly specified in INLINE_CODE_82 and the source path exists. Run INLINE_CODE_83 to download modules. |
| Backend initialization fails | Check AWS credentials and permissions. Verify S3 bucket and DynamoDB table exist or set INLINE_CODE_84 in remote_state config. |
| Dependency outputs not found | Ensure dependency module is applied first. Use INLINE_CODE_85 for planning without dependencies. Check INLINE_CODE_86 points to correct directory. |
| "Working directory already exists" error | Clear Terragrunt cache: INLINE_CODE_87 then run INLINE_CODE_88 again. Or use INLINE_CODE_89 flag. |
| Module source not updating | Force source update with INLINE_CODE_90 or delete INLINE_CODE_91 directory to clear cached modules. |
| State lock acquisition timeout | Another process holds the lock. Wait for completion or manually release lock in DynamoDB table. Check for crashed processes. |
| "Module not found" with relative paths | Use INLINE_CODE_92 to locate root config. Ensure relative paths account for Terragrunt's working directory structure. |
| Run-all commands fail partially | Check individual module errors with INLINE_CODE_93. Verify dependencies are correctly defined. Use INLINE_CODE_94 cautiously. |
| Permission denied errors on AWS | Verify IAM role/user has required permissions. Check if INLINE_CODE_95 in provider config is correct. Ensure MFA token is valid if required. |
| Circular dependency detected | Review INLINE_CODE_96 blocks to identify circular references. Restructure modules to break the cycle. Use INLINE_CODE_97 to visualize. |
| Variables not being passed correctly | Check INLINE_CODE_98 block syntax in INLINE_CODE_99. Verify variable names match module definitions. Use INLINE_CODE_100 to inspect final config. |
| Performance issues with many modules | Adjust INLINE_CODE_101 to optimize concurrent executions. Consider splitting into smaller module groups. Use INLINE_CODE_102 for selective runs. |
| _ | |
| Schnell. Referenz: Terragrunt vs Terraform Commands |
| Terragrunt Command | Equivalent Terraform | Key Difference |
|---|---|---|
| INLINE_CODE_103 | INLINE_CODE_104 | Auto-configures backend from INLINE_CODE_105 |
| INLINE_CODE_106 | INLINE_CODE_107 | Includes Terragrunt-managed inputs and dependencies |
| INLINE_CODE_108 | INLINE_CODE_109 | Processes dependencies and generates configs |
| INLINE_CODE_110 | N/A | Executes across multiple modules with dependency ordering |
| INLINE_CODE_111 | INLINE_CODE_112 | Can aggregate outputs from multiple modules |
| _ | terragrunt graph-dependencies |
N/A |