Pular para o conteúdo

Guia Rápido do Terragrunt

Guia Rápido do Terragrunt

Instalação

PlataformaComando
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
Dockerdocker 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 Installationterragrunt --version

Comandos Básicos

ComandoDescrição
terragrunt initInicialize o Terraform com configuração de backend gerenciada automaticamente
terragrunt planGerar e mostrar plano de execução para mudanças de infraestrutura
terragrunt applyAplicar alterações de infraestrutura (solicita confirmação)
terragrunt apply -auto-approveAplicar alterações sem confirmação interativa
terragrunt destroyDestruir todos os recursos de infraestrutura gerenciados
terragrunt destroy -auto-approveDestruir recursos sem prompt de confirmação
terragrunt validateValidar sintaxe de configuração do Terragrunt e Terraform
terragrunt fmtFormatar arquivos de configuração do Terraform para o estilo canônico
terragrunt fmt -recursiveRecursively format all .tf files in subdirectories
terragrunt outputExibir todos os valores de saída do estado
terragrunt output <name>Display specific output value (e.g., terragrunt output vpc_id)
terragrunt output -jsonExibir saídas no formato JSON para análise
terragrunt showExibir estado atual ou plano salvo em formato legível por humanos
terragrunt consoleAbrir console interativo para testar expressões
terragrunt refreshAtualizar arquivo de estado com status real da infraestrutura
terragrunt state listListe todos os recursos rastreados no arquivo de estado
terragrunt state show <resource>Mostrar informações detalhadas de estado para recurso específico
terragrunt workspace listListar todos os workspaces disponíveis
terragrunt workspace select <name>Mudar para o workspace especificado
terragrunt workspace new <name>Criar e alternar para novo workspace

Uso Avançado

ComandoDescrição
terragrunt run-all planExecutar plano em todos os módulos na ordem de dependência
terragrunt run-all applyAplicar alterações a todos os módulos respeitando dependências
terragrunt run-all destroyDestruir todos os módulos em ordem reversa de dependência
terragrunt run-all initInicializar todos os módulos na árvore de diretórios
terragrunt run-all validateValidar todas as configurações do módulo
terragrunt run-all outputExibir saídas de todos os módulos
terragrunt graph-dependenciesGerar e exibir grafo de dependências de módulo
terragrunt render-jsonRenderizar configuração final como JSON para inspeção
terragrunt hclfmtFormat terragrunt.hcl configuration files
terragrunt state mv <source> <dest>Mover recurso para endereço diferente no estado
terragrunt state rm <resource>Remover recurso do estado sem destruí-lo
terragrunt import <address> <id>Importar infraestrutura existente para o estado do Terraform
terragrunt taint <resource>Marcar recurso para recreação no próximo apply
terragrunt untaint <resource>Remover marcação de taint do recurso
terragrunt plan -out=tfplanSalvar plano de execução em arquivo para aplicação posterior
terragrunt apply tfplanAplicar arquivo de plano salvo anteriormente
terragrunt plan --terragrunt-log-level debugExecutar plano com registro de depuração detalhado
terragrunt run-all apply --terragrunt-parallelism 3Limitar a execução de módulos paralelos para 3 operações simultâneas
terragrunt apply --terragrunt-source ../local-moduleSubstituir fonte do módulo para desenvolvimento/teste local
terragrunt run-all apply --terragrunt-include-dir vpcExecute apenas em diretórios de módulos específicos
terragrunt run-all apply --terragrunt-exclude-dir legacyExcluir diretórios específicos da execução
terragrunt apply --terragrunt-include-external-dependenciesIncluir dependências externas na execução
terragrunt init -reconfigureReconfigurar backend, ignorando configuração existente
terragrunt init -upgradeAtualizar plugins de provedor para as últimas versões permitidas
terragrunt state pull > terraform.tfstateBaixar e salvar estado remoto localmente

Configuração

Estrutura Básica do 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"
}

Configuração de Estado Remoto (terragrunt.hcl Raiz)

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

Configuração de Dependência

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

Gerar Configuração de Provider

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

Locais e Funções

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

Configuração de Hooks

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

Casos de Uso Comuns

Caso de Uso 1: Configuração de Infraestrutura Multi-Ambiente

# 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

Caso de Uso 2: Gerenciando Dependências de Módulos

# 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

Caso de Uso 3: Desenvolvimento de Módulo Local

# 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

Caso de Uso 4: Gerenciamento e Migração de Estado

# 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

Caso de Uso 5: Depuração e Solução 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 '.'

Melhores Práticas

  • Use o princípio DRY: Mantenha a configuração de backend na raiz terragrunt.hcle inclua-a em módulos filhos usando blocos includepara evitar duplicação
  • Versione seus módulos: Sempre fixe as fontes dos módulos em versões ou tags específicas (por exemplo, ?ref=v1.0.0) para garantir implantações reproduzíveis
  • Implemente gerenciamento de dependências: Use blocos dependencypara definir explicitamente relacionamentos entre módulos em vez de depender da ordem de execução manual
  • Aproveite locais e funções: Use as funções internas do Terragrunt comofind_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

ProblemaSolução
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 failsCheck AWS credentials and permissions. Verify S3 bucket and DynamoDB table exist or set skip_bucket_creation = false in remote_state config.
Dependency outputs not foundEnsure dependency module is applied first. Use mock_outputs for planning without dependencies. Check config_path points to correct directory.
”Working directory already exists” errorClear Terragrunt cache: rm -rf .terragrunt-cache then run terragrunt init again. Or use --terragrunt-source-update flag.
Module source not updatingForce source update with terragrunt init --terragrunt-source-update or delete .terragrunt-cache directory to clear cached modules.
State lock acquisition timeoutOutro processo detém o lock. Aguarde a conclusão ou libere manualmente o lock na tabela DynamoDB. Verifique processos travados.
”Module not found” with relative pathsUse find_in_parent_folders() to locate root config. Ensure relative paths account for Terragrunt’s working directory structure.
Run-all commands fail partiallyCheck individual module errors with --terragrunt-log-level debug. Verify dependencies are correctly defined. Use --terragrunt-ignore-dependency-errors cautiously.
Permission denied errors on AWSVerify IAM role/user has required permissions. Check if role_arn in provider config is correct. Ensure MFA token is valid if required.
Circular dependency detectedReview dependency blocks to identify circular references. Restructure modules to break the cycle. Use terragrunt graph-dependencies to visualize.
Variables not being passed correctlyCheck inputs block syntax in terragrunt.hcl. Verify variable names match module definitions. Use terragrunt render-json to inspect final config.
Performance issues with many modulesAdjust --terragrunt-parallelism to optimize concurrent executions. Consider splitting into smaller module groups. Use --terragrunt-include-dir for selective runs.

Quick Reference: Terragrunt vs Terraform Commands

Comando TerragruntTerraform EquivalenteDiferença Principal
terragrunt initterraform initAuto-configures backend from terragrunt.hcl
terragrunt planterraform planInclui entradas e dependências gerenciadas pelo Terragrunt
terragrunt applyterraform applyProcessa dependências e gera configurações
terragrunt run-all applyI apologize, but there is no text provided to translate. Could you please share the specific English text you would like me to translate to Portuguese?Executa através de múltiplos módulos com ordenação de dependência
terragrunt outputterraform outputPode agregar saídas de múltiplos módulos