Day-09: terraform의 라이프사이클 관리 규칙

발행: (2025년 12월 3일 오후 01:21 GMT+9)
4 min read
원문: Dev.to

Source: Dev.to

Lifecycle rules

Terraform에서 라이프사이클 규칙은 리소스가 생성, 업데이트 및 삭제되는 방식을 제어합니다. 보안을 강화하고 유지 관리를 단순화하며 리소스에 대한 보다 세밀한 제어를 제공하는 데 도움이 됩니다.

Terraform은 다음 여섯 가지 라이프사이클 인수를 제공합니다:

  • ignore_changes
  • prevent_destroy
  • replace_triggered_by
  • create_before_destroy
  • precondition
  • postcondition

1. create_before_destroy

리소스를 변경해야 할 때, 이 규칙은 기존 리소스를 파괴하기 앞에 새 버전을 생성하여 다운타임을 최소화합니다(무중단 배포).

// main.tf
resource "aws_instance" "instance" {
  ami           = "ami-0f64121fa59598bf7"
  instance_type = "t3.micro"
  region        = tolist(var.allowed_region)[0]

  tags = var.tags

  lifecycle {
    create_before_destroy = true
  }
}

2. prevent_destroy

리소스가 실수로 삭제되는 것을 방지합니다.

// main.tf
resource "aws_s3_bucket" "bucket" {
  bucket = "${var.username}-bucket-${var.environment}-day-09"

  lifecycle {
    prevent_destroy = true
  }
}

3. ignore_changes

Terraform 외부에서 리소스에 가해진 변경(예: 수동 태그 편집)을 무시합니다.

// main.tf
resource "aws_instance" "instance" {
  ami           = "ami-0f64121fa59598bf7"
  instance_type = "t3.micro"
  region        = tolist(var.allowed_region)[0]

  tags = var.tags

  lifecycle {
    ignore_changes = [tags]
  }
}

4. replace_triggered_by

지정된 속성이 변경될 때 리소스 교체를 강제합니다.

// main.tf
resource "aws_instance" "instance" {
  ami           = "ami-0f64121fa59598bf7"
  instance_type = "t3.micro"
  region        = tolist(var.allowed_region)[0]

  tags = var.tags

  lifecycle {
    replace_triggered_by = [instance_type]
  }
}

5. precondition

리소스를 생성하거나 업데이트하기 조건을 검증합니다.

// main.tf
resource "aws_instance" "instance" {
  ami           = "ami-0f64121fa59598bf7"
  instance_type = "t3.micro"
  region        = tolist(var.allowed_region)[0]

  tags = var.tags

  lifecycle {
    precondition {
      condition     = var.instance_type == "t3.micro"
      error_message = "Instance type must be t3.micro"
    }
  }
}

6. postcondition

리소스가 생성되거나 업데이트된 조건을 검증합니다.

// main.tf
resource "aws_instance" "instance" {
  ami           = "ami-0f64121fa59598bf7"
  instance_type = "t3.micro"
  region        = tolist(var.allowed_region)[0]

  tags = var.tags

  lifecycle {
    postcondition {
      condition     = aws_instance.instance.instance_state == "running"
      error_message = "Instance is not in running state"
    }
  }
}

Best practices

  • 라이프사이클 규칙을 사용하여 리소스를 효과적으로 관리합니다.
  • 프로덕션에 적용하기 전에 비프로덕션 환경에서 라이프사이클 규칙을 테스트합니다.
  • Terraform 코드에 사용된 라이프사이클 규칙을 문서화하여 이해도와 유지 보수를 향상시킵니다.
  • 요구 사항이 변함에 따라 라이프사이클 규칙을 정기적으로 검토하고 업데이트합니다.
  • ignore_changes 사용에 주의하세요; 중요한 수정 사항을 숨길 수 있습니다.
  • 다운타임을 방지하기 위해 중요한 리소스에는 create_before_destroy를 적용합니다.

@piyushsachdeva

Back to Blog

관련 글

더 보기 »

AWS Terraform 라이프사이클 규칙

소개 인프라스트럭처 코드(IaC)는 업데이트, 교체 및 삭제 시 리소스가 어떻게 동작하는지에 대한 완전한 제어가 있을 때 가장 강력합니다. Terr...