본문 바로가기

IaC/Terraform

[Terraform]조건문(Conditional)을 사용하여 resource 작성하는 방법

조건부 표현식(Conditional Expression)의 이해

  • 조건부 표현식은 "조건 ? 참일 경우의 값 : 거짓일 경우의 값"의 형태로 사용됩니다. 이는 프로그래밍 언어에서 자주 볼 수 있는 삼항 연산자와 동일한 형태입니다.
  • 이런 식으로 Terraform에서는 변수나 리소스의 값을 동적으로 결정할 수 있습니다.

왜 조건부 표현식이 필요한가?

  • 인프라의 설정이나 배포 과정에서 모든 상황에 동일한 설정을 사용하는 것은 비효율적입니다. 예를 들면, 개발 환경과 실제 환경에서는 다른 설정이 필요할 수 있습니다.
  • 이런 다양한 상황에 대응하기 위해 동적으로 리소스나 출력 값을 결정하는 것이 필요하고, 이때 조건부 표현식이 유용하게 사용됩니다.

var 옵션으로 변수 재정의

tf apply -var="변수명=값" 형태로 명령을 실행하면, 기존 Terraform 코드에 정의된 변수의 기본값을 재정의하여 실행할 수 있습니다.

이를 통해 동적인 환경에서 유연하게 Terraform 코드를 실행할 수 있습니다. 예를 들면, 개발 환경에서는 인터넷 게이트웨이를 활성화하지 않고, 실제 환경에서만 활성화할 수 있습니다.

사용방법 - 조건 ? If_True : If_False

provider "aws" {
    region = "ap-northeast-2"  
}

# conditional expression
## ?, : 을 사용하여 표현
## 조건 ? If_True : If_False

variable "is_jeff" {
    type = bool
    default = true
}

locals {
  message = var.is_jeff ? "hello jeff" : "not jeff"
}

output "message" {
    value = local.message
}

결과 - tf apply

 tf apply

Changes to Outputs:
  + message = "hello jeff"

You can apply this plan to save these new output values to the Terraform
state, without changing any real infrastructure.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

message = "hello jeff"

결과 - 조건을 false로 변경

tf apply -var="is_jeff=false"

 tf apply -var="is_jeff=false"   

Changes to Outputs:
  ~ message = "hello jeff" -> "not jeff"

You can apply this plan to save these new output values to the Terraform
state, without changing any real infrastructure.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

message = "not jeff"

Resource에서 조건문 사용하기

# 리소스에서 조건문 사용하기
variable "internet_gateway_enabled" {
    type = bool
    default = true
}

resource "aws_vpc" "vpc_with_ig" {
    cidr_block = "10.3.0.0/16"
}

resource "aws_internet_gateway" "ig_from_conditional" {
    count = var.internet_gateway_enabled ? 1 : 0
    vpc_id = aws_vpc.vpc_with_ig.id
}

vpc를 만들때 internet_gateway_enabled의 조건에 따라 ig를 만든다.

  • internet gateway는 vpc에 종속되는 리소스

count와 조건부 표현식을 함께 사용하면, 특정 조건에 따라 리소스를 생성할지 말지 결정할 수 있습니다. 예제에서는 internet_gateway_enabled 값이 참일 때만 인터넷 게이트웨이가 생성됩니다.

결과 - tf apply

# 중략
Plan: 2 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_vpc.vpc_with_ig: Creating...
aws_vpc.vpc_with_ig: Creation complete after 2s [id=vpc-01f190b049c193c0b]
aws_internet_gateway.ig_from_conditional[0]: Creating...
aws_internet_gateway.ig_from_conditional[0]: Creation complete after 1s [id=igw-0acb9b2d78018d8ba]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:

결과 - 조건을 false로 변경

# 중략
Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_internet_gateway.ig_from_conditional[0]: Destroying... [id=igw-0acb9b2d78018d8ba]
aws_internet_gateway.ig_from_conditional[0]: Destruction complete after 0s

Apply complete! Resources: 0 added, 0 changed, 1 destroyed.

tf apply -var="internet_gateway_enabled=false"