DevOps/Terraform

[Terraform] 테라폼 lifecycle의 precondition

Jflip 2024. 6. 16. 03:40
728x90

Terraform의 precondition은 리소스를 생성하거나 변경하기 전에 특정 조건이 만족되는지 확인하기 위해 사용되는 기능입니다. precondition을 사용하면 조건이 만족되지 않을 경우 리소스 생성이나 변경을 중단하고 사용자 정의 에러 메시지를 출력할 수 있습니다. 이는 리소스 생성을 위한 사전 조건을 정의할 때 매우 유용합니다.

 

주요 구성 요소

 

condition: 조건식을 정의하며, 이 조건이 true일 때만 리소스 생성 또는 변경이 진행됩니다.

error_message: 조건이 false일 때 출력될 사용자 정의 에러 메시지입니다.

 

 

1. variables.tf

variable "file_name" {

  description = "Name of the file to be created"

  default     = "step0.txt"

}

 

 

2. main.tf

resource "local_file" "abc" {
  content  = "lifecycle - step 6"
  filename = "${path.module}/${var.file_name}"

  lifecycle {
    precondition {
      condition     = contains(["step0.txt", "step1.txt", "step2.txt", "step3.txt", "step4.txt", "step5.txt", "step6.txt"], var.file_name)
      error_message = "설정된 값이 다음의 파일을 포함하지 않습니다. (step0.txt, step1.txt, step2.txt, step3.txt, step4.txt, step5.txt, step6.txt)"
    }
  }
}

 

3. terraform.tfvars

file_name = "step0.txt"

 

 

변수 값을 다음과 같이 steps0.txt로 설정합니다.

 

실행 결과 :

 

파일이 생성됩니다.

 

terraform.tfvars에 해당하지 않는 값을 설정합니다.

file_name = "step777.txt"

 

terraform apply시 다음과 같이 오류가 나는 것을 확인할 수 있습니다.

 

이후에 다시 steps6.txt로 테스트해봅니다.

파일이 다시 생성되는 것을 볼 수 있습니다.

728x90
반응형