Terragrunt

__HTML_TAG_117_📄 Generare Terragrunt PDF Guide_HTML_TAG_118__ __HTML_TAG_119_ # Terragrunt Cheatsheet ## Installazione _Tabella_121__ # Comandi di base _Tabella_122__ ## Uso avanzato _Tabella_123__ ## Configurazione ### Basic terragrunt.hcl Struttura
# 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"
}
### Configurazione di Stato remoto (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"
  }
}
### Configurazione della dipendenza
# 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
}
## # Generate Provider Configuration
# 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
}
## Locali e funzioni
# 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
  }
)
# Configurazione dei ganci
# 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: Gestione delle dipendenze del modulo
# 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: Debugging and Troubleshooting
# 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 '.'
# Migliori Pratiche - **Utilizza il principio DRY**: Mantenere la configurazione backend in root `terragrunt.hcl` e includerlo in moduli per bambini utilizzando blocchi `include`_ per evitare duplicazioni - *Versione dei moduli * Sempre pin sorgenti del modulo a specifiche versioni o tag (ad esempio `?ref=v1.0.0`) per garantire implementazioni riproducibili - ** Gestione della dipendenza dall'attuazione ** Utilizzare blocchi `dependency` per definire esplicitamente i rapporti tra i moduli piuttosto che affidarsi all'ordine di esecuzione manuale - **Leverage locals and function**: Utilizzare le funzioni integrate di Terragrunt come `find_in_parent_folders()`, `get_aws_account_id()`_, e `path_relative_to_include()`_ per la configurazione dinamica - **Utilizzare le uscite di mock**: Definire `mock_outputs` in blocchi di dipendenza per abilitare la validazione e la pianificazione senza richiedere l'applicazione di tutte le dipendenze - **Organizzare per ambiente**: directory struttura per ambiente (dev/staging/prod) con configurazione condivisa a livello root per coerenza - Abilita' di blocco dello stato. Configurare sempre le tabelle DynamoDB per bloccare lo stato quando si utilizza il backend S3 per evitare conflitti di modifica contemporaneamente - Si'. Provare con `run-all plan` prima `run-all apply` e prendere in considerazione l'utilizzo `--terragrunt-parallelism`_ per controllare le esecuzioni contemporaneamente - **Il fornitore di Generate configura**: Utilizzare blocchi `generate`_ per creare configurazioni dei provider in modo dinamico, garantendo coerenza tra i moduli - **I ganci per l'automazione**: Utilizzare `before_hook` e `after_hook`_ per automatizzare le attività come convalida, notifiche o controlli di conformità ## Risoluzione dei problemi _Tabella_124__ # Riferimento: 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` | Mostra dipendenze del modulo Terragrunt (non grafico delle risorse) |