IaC(Infrastructure as Code)

AWS + Terraform (Conditions)

cwchoiit 2024. 3. 7. 08:55
728x90
반응형
SMALL
728x90
SMALL

HCL은 조건문도 사용할 수 있다. Variables와 Condition을 조합해서 한번 조건문을 다뤄보자.

Basic

다음 main.tf 코드를 보자.

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

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

locals {
  message = var.is_john ? "Hello John" : "Oh, Your are not John."
}

output "message" {
  value = local.message
}

 

변수로 is_john이라는 녀석을 선언한다. 이 녀석은 boolean 타입의 변수고 기본값이 true이다.

이 때 로컬 변수 message는 is_john의 값에 따라 값이 달라진다. 이 부분에서 조건문이 사용된다. 삼항 연산자로 익숙하다.

 

이 간단한 코드를 실행해보면 다음과 같은 결과를 얻는다.

 

이 때 is_john의 값을 false로 변경하면 당연히 다음과 같은 결과를 얻는다. 이전에 Variables 포스팅에서 알아보았던 실행 시 옵션으로 변수값을 설정하는 방법으로 실행해보자.

 

 

Advanced

이번엔 이 조건문을 좀 더 응용해서 count와 같이 사용해보자. 왜 count와 같이 사용해야 하는 경우가 생기냐면, 리소스를 생성할 땐 그 리소스를 생성할지 말지를 정할 수 있는 방법이 count가 대표적으로 사용되기 때문이다. 다음 main.tf 파일을 보자.

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

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

resource "aws_vpc" "this" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_internet_gateway" "this" {
  count = var.internet_gateway_enabled ? 1 : 0

  vpc_id = aws_vpc.this.id
}

 

여기서 보면 AWS 인터넷 게이트웨이 리소스를 변수값에 따라 생성할지 말지를 count로 구분한다. 이렇게 조건문과 count를 같이 사용해서 리소스를 생성할지 말지를 결정할 수도 있다.

 

728x90
반응형
LIST

'IaC(Infrastructure as Code)' 카테고리의 다른 글

Terraform State  (0) 2024.03.07
AWS + Terraform (Loop)  (0) 2024.03.07
AWS + Terraform (For-Each)  (0) 2024.03.06
AWS + Terraform (Module)  (0) 2024.03.06
AWS + Terraform  (2) 2024.03.05