콘텐츠로 이동

Include root configuration

플랫폼명령어
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
명령어설명
terragrunt initTerraform 백엔드 구성을 자동으로 관리하여 초기화하기
terragrunt plan인프라 변경에 대한 실행 계획 생성 및 표시
terragrunt apply인프라 변경 사항 적용 (확인 프롬프트)
terragrunt apply -auto-approve상호작용 확인 없이 변경 사항 적용
terragrunt destroy모든 관리되는 인프라 리소스 제거
terragrunt destroy -auto-approve확인 프롬프트 없이 리소스 제거
terragrunt validateTerragrunt 및 Terraform 구성 구문 검증
terragrunt fmtTerraform 구성 파일을 표준 스타일로 포맷팅
terragrunt fmt -recursiveRecursively format all .tf files in subdirectories
terragrunt output상태의 모든 출력 값 표시
terragrunt output <name>Display specific output value (e.g., terragrunt output vpc_id)
terragrunt output -jsonJSON 형식으로 출력 결과 표시
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 hclfmtFormat 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원격 상태를 로컬로 다운로드하고 저장하기
# 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"
}
```## 고급 사용법
```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"
  }
}
```## 구성

### 기본 terragrunt.hcl 구조
```hcl
# 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
}

원격 상태 구성 (루트 terragrunt.hcl)

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

로컬 및 함수

# 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

훅 구성

# 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

일반적인 사용 사례

사용 사례 1: 다중 환경 인프라 설정

# 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

사용 사례 2: 모듈 의존성 관리

# 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

사용 사례 3: 로컬 모듈 개발

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

사용 사례 4: 상태 관리 및 마이그레이션

terragrunt.hcl

사용 사례 5: 디버깅 및 문제 해결

include

모범 사례

  • DRY 원칙 사용: 백엔드 구성을 루트에 보관하고?ref=v1.0.0중복을 방지하기 위해 dependency블록을 사용하여 자식 모듈에 포함
  • 모듈 버전 관리: 항상 모듈 소스를 특정 버전이나 태그에 고정 (예: 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 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 timeout다른 프로세스가 잠금을 보유하고 있습니다. 완료를 기다리거나 DynamoDB 테이블에서 잠금을 수동으로 해제하세요. 충돌한 프로세스를 확인하세요.
”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

Terragrunt 명령어동등한 Terraform주요 차이점
terragrunt initterraform initAuto-configures backend from terragrunt.hcl
terragrunt planterraform planTerragrunt 관리 입력 및 종속성 포함
terragrunt applyterraform apply프로세스 종속성을 처리하고 구성을 생성합니다
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 Korean?의존성 순서에 따라 여러 모듈에서 실행됩니다
terragrunt outputterraform output여러 모듈의 출력을 집계할 수 있음