DevOps/Terraform

[TF]Terraform 조건문

Michael Kim 2021. 12. 21. 23:05

Terraform에서는 조건식을 지원한다.

 조건식 Condition ? If_True : If_False를 사용하여 나타낼 수 있다.


예제

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

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

locals {
  message = var.is_jhon ? "Hello John!":"Hello!"
}

output "message" {
  value = local.message
}

위의 코드에서 값이 True면 Hello John!을 출력하게 되고 Flase면 Hello!를 출력하게된다.


조건식을 활용한 IGW 

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
}

VPC가 생성되고 IGW는 default의 값이 Ture이기 때문에 생성된다.

AWS Console에서도 정상적으로 VPC, IGW가 생성된걸 볼 수 있다.

IGW의 VPC도 새로 생성된 VPC임을 확인 할 수 있다.

이로써 vpc-052151c1e8e31e354는 IGW를 통해 외부 인터넷과 통신이 가능하다.

 

추가로 variable "internet_gateway_enabled"에서 default를 False로 변경하면 VPC만 생성된다.