연재 시리즈

테라폼 시리즈 32편. 조건문 - 3항 연산자

악분 2022. 11. 19. 10:48
반응형

사용방법

테라폼은 3항 연산자를 지원합니다. 3항 연산자는 간단한 조건문(타입 검사 등)을 구현할 때 적합합니다.

<조건> ? <조건 만족> : <조건 불만족>

 

예제1 - string타입 검사

아래 테라폼 코드는 instance_type을 검사하여 aws EC2 Instance를 생성하는 예제입니다. instance_type은 3항 연산자 조건문 결과로 설정됩니다. 3항 연산자는 variable ec2_type이 빈값이면 t2_nano로 설정합니다.

코드링크: https://github.com/sungwook-practice/terraform-study/tree/main/week5/condition/condition-basic
provider "aws" {
  region  = "ap-northeast-2"
}

variable ec2_type {
  type        = string
  default     = ""
  description = "description"
}


data "aws_ami" "last_ami" {
  most_recent = true

  filter {
    name   = "owner-alias"
    values = ["amazon"]
  }

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-ebs"]
  }

  owners = ["amazon"]
}

resource "aws_instance" "server" {
  count = 1

  ami           = data.aws_ami.last_ami.id
  instance_type = var.ec2_type != "" ? var.ec2_type : "t2.nano"

  tags = {
    Name = "Server ${count.index}"
  }
}

 

위 예제는 결과적으로 3항 연산자로 instance_type default 값을 설정합니다. 읽기쉬운 코드로 리팩토링을 한다면 3항 연산자보다는 variable default를 사용하는 걸로 변경할 수 있습니다.

variable ec2_type {
  type        = string
  default     = "t2.nano"
  description = "description"
}

resource "aws_instance" "server" {
  count = 1

  ami           = data.aws_ami.last_ami.id
  instance_type = var.ec2_type

  tags = {
    Name = "Server ${count.index}"
  }
}

 

예제2 - bool타입 검사: count meta argument와 연계

bool타입은 true, false 값을 가지므로 on/off 역할에 많이 사용합니다.

 

대표적인 예가 count meta argument입니다. count가 0이면 block을 생성하지 않고 1이상이면 block을 생성합니다. 그래서 block생성여부를 3항 연산자로 true/false인지 검사할 수 있습니다. true이면 count가 1, false이면 count가 0으로 설정합니다.

 

아래 예제는 internet gateway를 3항 연산자와 count로 생성여부를 검사합니다.

variable "create_igw" {
  description = "Controls if an Internet Gateway is created for public subnets and the related routes that connect them."
  type        = bool
  default     = true
}

resource "aws_internet_gateway" "akbun-igw" {
  count = var.create_igw ? 1 : 0

  vpc_id = aws_vpc.akbun-vpc.id

  tags = {
    Name = "t101-igw"
  }
}

 

전체 코드는 아래와 같습니다.

코드링크: https://github.com/sungwook-practice/terraform-study/tree/main/week5/condition/condition-count
# reference: https://github.com/terraform-aws-modules/terraform-aws-vpc/blob/master/variables.tf#L1194
variable "create_igw" {
  description = "Controls if an Internet Gateway is created for public subnets and the related routes that connect them."
  type        = bool
  default     = true
}

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

resource "aws_vpc" "akbun-vpc" {
  cidr_block       = "10.10.0.0/16"
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "t101-study"
  }
}

resource "aws_subnet" "akbun-subnet1" {
  vpc_id     = aws_vpc.akbun-vpc.id
  cidr_block = "10.10.1.0/24"

  availability_zone = "ap-northeast-2a"

  tags = {
    Name = "t101-subnet1"
  }
}

resource "aws_internet_gateway" "akbun-igw" {
  count = var.create_igw ? 1 : 0

  vpc_id = aws_vpc.akbun-vpc.id

  tags = {
    Name = "t101-igw"
  }
}

resource "aws_route_table" "myrt" {
  vpc_id = aws_vpc.akbun-vpc.id

  tags = {
    Name = "t101-rt"
  }
}

resource "aws_route_table_association" "myrtassociation1" {
  subnet_id      = aws_subnet.akbun-subnet1.id
  route_table_id = aws_route_table.myrt.id
}

resource "aws_route" "mydefaultroute" {
  route_table_id         = aws_route_table.myrt.id
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = aws_internet_gateway.akbun-igw[0].id
}

output "my_vpc_id" {
  value       = aws_vpc.akbun-vpc.id
  description = "vpc"
}
반응형