Saltar a contenido
_

Terragrunt Cheatsheet

Instalación

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

Comandos básicos

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

Advanced Usage

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

Configuración

Basic terragrunt.hcl Estructura

# 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"
  }
}

Configuración de dependencia

# 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
}

Generar configuración del proveedor

# 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
}

Locales y Funciones

# 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
  }
)

Configuración de ganchos

# 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
  }
}

Common Use Cases

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: Managing Module Dependencies

# 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 and 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: Depuración y solución de problemas

# 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 '.'

Buenas prácticas

  • Utilizar el principio DRY: Mantener la configuración de backend en root terragrunt.hcl e incluirlo en módulos infantiles usando bloques __INLINE_CODE_68_ para evitar duplicaciones
  • Version sus módulos: Siempre hay fuentes de módulos para versiones o etiquetas específicas (por ejemplo, ?ref=v1.0.0) para garantizar despliegues reproducibles ** Gestión de la dependencia de la ejecución**: Use dependency bloques para definir explícitamente las relaciones entre módulos en lugar de confiar en el orden de ejecución manual Los locales y las funciones Usar las funciones incorporadas de Terragrunt como find_in_parent_folders(), get_aws_account_id() y path_relative_to_include() para la configuración dinámica
  • Use mock outputs: Define mock_outputs en bloques de dependencia para permitir la validación y planificación sin requerir que todas las dependencias se apliquen primero
  • Organizar por medio ambiente: Dirección de estructuras por medio del medio ambiente (dev/staging/prod) con configuración compartida a nivel raíz para la coherencia
  • ¿Qué? Configure siempre tablas DynamoDB para bloqueo de estado cuando use backend S3 para evitar conflictos de modificación simultánea
  • ¿Por qué? Prueba con run-all plan_ antes run-all apply_ y considera usar --terragrunt-parallelism para controlar las ejecuciones simultáneas
  • Configuración del proveedor de genes: Utilizar bloques generate para crear configuraciones de proveedores dinámicamente, asegurando la coherencia entre módulos
  • Los ganchos de implementación para la automatización: Use before_hook y after_hook para automatizar tareas como validación, notificaciones o cheques de cumplimiento

Troubleshooting

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.

Quick Referencia: 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_ Silencio N/A Silencio Shows dependencias del módulo Terragrunt (no gráfico de recursos)