devops2023-09-10·8 min·340/348

Terraform State 충돌 문제 해결

Terraform state 파일의 충돌 문제를 진단하고 해결하는 방법을 알아봅니다.

Terraform State 충돌 문제 해결

Terraform state 파일은 인프라 리소스를 추적하는 데 사용됩니다. 동시 작업 시 state 충돌이 발생하면 심각한 문제를 일으킬 수 있습니다.

Environment

$ terraform version
Terraform v1.6.6
on linux_amd64

$ aws --version
aws-cli/2.15.12 Python/3.11.6

Problem: Concurrent State Lock Error

$ terraform apply
Acquiring state lock. This may take a few moments...

Error: Error acquiring the state lock

Error message: ConditionalCheckFailedException: The conditional request failed
Lock Info:
  ID:        a1b2c3d4-e5f6-7890-abcd-ef1234567890
  Path:      my-bucket/terraform.tfstate
  Operation: OperationTypeApply
  Who:       joel@workstation
  Version:   1.6.6
  Created:   2024-01-15 10:30:00.123456 +0000 UTC

또는:

Error: state file is locked
Lock ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890

Analysis: State Locking 동작 원리

# Terraform uses state locking to prevent concurrent modifications
# Default: DynamoDB table for AWS S3 backend

# Check current lock
$ terraform force-unlock 
Do you really want to force-unlock?
  Only 'yes' will be accepted to confirm.

  Enter a value: yes

# Lock status check
$ aws dynamodb get-item \
  --table-name terraform-locks \
  --key '{"LockID":{"S":"my-bucket/terraform.tfstate"}}'

Solution: State 충돌 해결 방법

방법 1: Remote State 설정

# main.tf
terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "eu-west-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}
# Initialize remote backend
$ terraform init -reconfigure

방법 2: State Unlock

# List current locks
$ terraform force-unlock -help

# Force unlock with specific ID
$ terraform force-unlock a1b2c3d4-e5f6-7890-abcd-ef1234567890

# Or unlock by state path
$ terraform force-unlock -state=my-bucket/terraform.tfstate

방법 3: State 파일 관리

# State 파일 백업
$ terraform state pull > backup-$(date +%Y%m%d).tfstate

# State 파일 복구
$ terraform state push backup-20240115.tfstate

# State 이동
$ terraform state mv aws_instance.old aws_instance.new

# State 리네임
$ terraform state mv -state-out=new.tfstate aws_instance.web aws_instance.web

방법 4: Workspace 활용

# Create workspace
$ terraform workspace new staging
$ terraform workspace new production

# List workspaces
$ terraform workspace list

# Select workspace
$ terraform workspace select production

# State is isolated per workspace

방법 5: Import Existing Resources

# Import existing resource to state
$ terraform import aws_instance.web i-1234567890abcdef0

# Import with custom ID
$ terraform import 'aws_instance.web["web-server"]' i-1234567890abcdef0

Advanced: State 관리 Best Practices

# backend.tf
terraform {
  backend "s3" {
    bucket         = "company-terraform-state"
    key            = "projects/myproject/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
    
    # Enable state versioning
    version = "3"
  }
}

# Variables for state management
variable "environment" {
  description = "Deployment environment"
  type        = string
}

locals {
  state_key = "${var.environment}/terraform.tfstate"
}
# State file inspection
$ terraform show
$ terraform state list
$ terraform state show aws_instance.web

# Validate state
$ terraform validate

Troubleshooting Commands

# 1. Lock 상태 확인
$ terraform plan  # Will show lock status

# 2. Lock 해제
$ terraform force-unlock 

# 3. State 백업
$ terraform state pull > backup.tfstate

# 4. State 초기화
$ terraform init -reconfigure

# 5. State 파일 교체
$ terraform state push new-state.tfstate

# 6. Workspace 상태 확인
$ terraform workspace show
$ terraform workspace list

Lessons Learned

  1. Remote State 필수: 팀 프로젝트에서는 반드시 remote state를 사용하여 state 충돌을 방지하세요.

  2. Locking 메커니즘: DynamoDB나 Consul 같은 backend를 사용하여 state locking을 활성화하세요.

  3. 정기 백업: state 파일은 정기적으로 백업하여 장애 시 복구할 수 있도록 하세요.

  4. Workspace 활용: 환경별로 workspace를 분리하면 state 관리가 쉬워집니다.

  5. 버전 관리: state 파일은 버전 관리 시스템에 커밋하지 마세요 (민감한 정보 포함).


This blog does not accept any external sponsorships, affiliate marketing, or ad revenue.