[기본 구성 요소] Variables

2024. 11. 26. 01:40Terraform/[인프런] 아키텍처와 함께하는 Terraform

1. Variables

- Variables는 반복적이고 동적인 구성을 재사용성과 관리 용이성을 높이기 위해 사용된다.
- 유연성가독성을 크게 향상시킨다.

 

 

2. Variables 주요 특징

- 유연한 값 주입 : 명령줄, 환경 변수, 파일을 통해 설정 가능하다.
- 다양한 데이터 유형 지원 : string, number, bool, list, map, object 등 지원한다.
- 기본값 지원 : 변수가 설정되지 않았을 때 사용할 기본값 정의할 수 있다.
- 유효성 검증 : 변수 값의 조건을 설정하여 유효성 검사할 수 있다.

 

 

3. Variables 예제

- 변수 정의 예제 (varialbes.tf)
* 예제
variable "region" {                                        # varialbe "변수명"
  description = "The AWS region to deploy resources in"    # 변수 설명
  type        = string                                     # 변수 데이터 유형 
  default     = "ap-northeast-2"                           # 기본값을 서울 리전으로 하여 값이 설정되지 않은 경우 사용 
}

variable "instance_type" {
  description = "The EC2 instance type"
  type        = string
  default     = "t2.micro"
}

variable "tags" {
  description = "Tags to assign to the resources"
  type        = map(string)
  default = {
    Environment = "Dev"
    Project     = "TerraformExample"
  }
}
- 변수 사용 예제 (main.tf)
* 예제
provider "aws" {
  region = var.region                     # 변수 참조(var.변수명)
}

resource "aws_instance" "example" {
  ami           = "ami-0c1a7f89451184c8b" # 서울 리전에서 유효한 AMI ID
  instance_type = var.instance_type       # 변수 참조

  tags = var.tags                         # 태그 변수 참조
}
- 변수 값 설정 예제 (terraform.tfvars)
* 예제
region        = "us-west-1"
instance_type = "t3.medium"
tags = {
  Environment = "Production"
  Project     = "TerraformBlog"
}
- Validation(유효성 검증) 예제
- 변수 값이 t2.micro, t3.micro, t3.medium 중 하나인지 확인하고 조건을 만족하지 않으면 에러 메시지 출력한다.
* 예제
variable "instance_type" {
  description = "The EC2 instance type"
  type        = string
  default     = "t2.micro"

  validation {
    condition     = contains(["t2.micro", "t3.micro", "t3.medium"], var.instance_type)
    error_message = "The instance type must be one of t2.micro, t3.micro, or t3.medium."
  }
}
- 변수 없이 작성한 코드 비교 예제
- 변수 사용 후 코드가 유연해지고 재사용성이 높아졌다.
* 예제
* 변수 사용 전
provider "aws" {
  region = "ap-northeast-2"
}

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

  tags = {
    Environment = "Dev"
    Project     = "TerraformExample"
  }
}
* 변수 사용 후
provider "aws" {
  region = var.region
}

resource "aws_instance" "example" {
  ami           = "ami-0c1a7f89451184c8b"
  instance_type = var.instance_type
  tags          = var.tags
}