IaC👩‍💻/TerraForm

[Terraform] 조건문

nayeo2 2024. 8. 23. 11:44

조건문

  • 삼항 연산자 형태로 작성

기본 형식

condition ? true_value : false_value
  • condition : 평가되는 표현식. 이 표현식이 참이면 true_value가 반환되고, 거짓이면 false_value가 반환됨

예시


variable "count" {
  default = 3
}

output "result" {
  value = var.count > 5 ? "많음" : "적음"
}
  • 위 예시에서는 count = 3이므로, result로 적음을 반환.

리소스 내 조건문 사용


resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = var.environment == "production" ? "Prod Instance" : "Dev Instance"
  }
}

맵과 리스트에서 조건문 사용


variable "environment" {
  type    = string
  default = "development"
}

locals {
  config = {
    "development" = "dev-config"
    "production"  = "prod-config"
  }
}

output "config_file" {
  value = local.config[var.environment == "production" ? "production" : "development"]
}

응용

루트 모듈의 main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "ap-northeast-2"
}

variable "teammate_name" {
type = list(string)
default = ["dev", "deploy", ""]
}

module "employee_vpc_module" {
  for_each = toset([for name in var.teammate_name : name if name != ""])
  source = "./vpc_module"
  env = each.key
}
  • name이 ""가 아닌 경우에 생성

vpc_module/main.tf

resource "aws_subnet" "public_subnet1" {
  count = var.env == "deploy" ? 0 : 1
  vpc_id     = aws_vpc.example.id
  cidr_block = "10.0.1.0/24"
availability_zone = local.az_a

  tags = {
    Name = "swu_public_subnet1_${var.env}"
  }
}
  • count가 0이면 생성 되지 않고, 1 이상이면 생성