Day-12: AWS Terraform 함수

발행: (2025년 12월 6일 오전 02:48 GMT+9)
6 min read
원문: Dev.to

Source: Dev.to

Terraform의 고급 함수

Day 11에서 다룬 기본 함수를 바탕으로, 오늘은 Terraform이 복잡한 데이터 변환, 검증 및 작업을 처리할 수 있도록 해주는 보다 전문화된 함수들을 살펴봅니다. 이러한 함수들은 견고하고 프로덕션 수준의 인프라를 코드로 구현하는 데 필수적입니다.

고급 함수 유형

숫자 함수

숫자 함수는 수학 연산을 수행하고 숫자 값을 조작하는 데 사용됩니다. 계산, 절대값 연산, 통계 연산 및 기타 숫자 변환을 가능하게 합니다.

예시: abs(), ceil(), floor(), max(), min(), sum(), sqrt()

검증 함수

검증 함수는 입력 값을 검증하고 특정 기준을 충족하는지 확인하는 데 사용됩니다. 조건과 형식을 검사하여 데이터 무결성을 보장하고 구성 오류를 방지합니다.

예시: can(), regex(), length(), startswith(), endswith(), contains()

날짜/시간 함수

날짜 및 시간 함수는 날짜와 시간 값을 조작하고 포맷하는 데 사용됩니다. 파싱, 포맷팅, 타임스탬프 생성 및 시간 차이 계산을 가능하게 합니다.

예시: formatdate(), timeadd(), timestamp(), timecmp()

파일 함수

파일 함수는 파일 내용을 읽고, 조작하며, 파일 속성을 확인하는 데 사용됩니다. 파일 읽기, 존재 여부 확인, 파일 경로 작업 및 기타 파일 관련 작업을 수행할 수 있습니다.

예시: file(), fileexists(), dirname(), basename(), jsondecode(), jsonencode()

DAY‑12 예시

1. 숫자 함수 – 비용 분석 및 관리

절대값 및 통계 연산

// variables.tf
variable "monthly_cost" {
  description = "The estimated monthly cost"
  type        = list(number)
  default     = [-100.5, 200.75, 300.0]
}

// main.tf
locals {
  # Convert negative costs to absolute values
  absolute_monthly_cost = [for cost in var.monthly_cost : abs(cost)]

  # Find maximum cost using max() function
  maximum_monthly_cost = max(local.absolute_monthly_cost...)

  # Calculate total cost using sum() function
  total_monthly_cost = sum(local.absolute_monthly_cost)
}

// outputs.tf
output "absolute_monthly_cost" {
  value       = local.absolute_monthly_cost
  description = "The absolute values of the estimated monthly costs"
}

output "maximum_monthly_cost" {
  value       = local.maximum_monthly_cost
  description = "The maximum estimated monthly cost"
}

output "total_monthly_cost" {
  value       = local.total_monthly_cost
  description = "The total estimated monthly cost"
}

2. 검증 함수 – 입력 검증 및 품질 관리

정규식 검증 및 길이 확인

// variables.tf
variable "instance_type" {
  description = "The type of instance to use"
  type        = string
  default     = "t2.micro"

  validation {
    condition     = can(regex("^t[2-3]\\.", var.instance_type))
    error_message = "instance type must start with 't2.' or 't3.'"
  }

  validation {
    condition     = length(var.instance_type) > 2 && length(var.instance_type) < 20
    error_message = "length of instance type must be between 2 and 20 characters"
  }
}

variable "backup_file_name" {
  description = "The name of the backup file"
  type        = string
  default     = "bucket_backup"

  validation {
    condition     = endswith(var.backup_file_name, "_backup")
    error_message = "backup file must end with '_backup'"
  }
}

// main.tf
locals {
  instance_type    = var.instance_type
  backup_file_name = var.backup_file_name
}

// outputs.tf
output "instance_type" {
  value       = local.instance_type
  description = "The type of instance being used"
}

output "backup_file_name" {
  value = local.backup_file_name
}

3. 날짜/시간 함수 – 타임스탬프 관리

현재 타임스탬프 및 날짜 포맷팅

// main.tf
locals {
  # Get current timestamp
  current_time = timestamp()

  # Format timestamp to YYYY-MM-DD format
  formatted_time = formatdate("YYYY-MM-DD", local.current_time)

  # Create timestamped bucket name
  bucket_name_with_timestamp = "bhaskaratejabulusu-s3-bucket-${local.formatted_time}"
}

// outputs.tf
output "bucket_name_with_timestamp" {
  value       = local.bucket_name_with_timestamp
  description = "The S3 bucket name appended with the current timestamp"
}

4. 파일 함수 – 구성 파일 관리

파일 존재 여부 확인 및 JSON 처리

// main.tf
locals {
  # Check if config file exists
  config_file_exists = fileexists("./config.json")

  # Conditionally load file content based on existence
  file_config = local.config_file_exists ? jsondecode(file("./config.json")) : {}

  # Get directory name from file path
  directory_name_of_file = dirname("./config.json")

  # Read specific value from JSON file
  username = jsondecode(file("./config.json")).username
}

// Create JSON file from variable data
resource "local_file" "my_json_file" {
  content  = jsonencode(var.my_data)
  filename = "my_data.json"
}

// variables.tf
variable "my_data" {
  type = map(any)
  default = {
    name      = "bhaskara"
    age       = 30
    is_active = true
  }
}

// outputs.tf
output "file_config" {
  value       = local.file_config
  description = "The configuration loaded from config.json file"
}

output "directory_name_of_file" {
  value       = local.directory_name_of_file
  description = "The directory name of the config.json file"
}

output "username" {
  value       = local.username
  description = "The username from the config file or default"
}

5. 컬렉션 함수와 타입 변환 – 리전 관리

집합 연산 및 리스트 연결

// variables.tf
variable "default_regions" {
  type    = list(string)
  default = ["us-east-1", "us-west-2", "us-east-1"]
}

variable "new_regions" {
  type    = list(string)
  default = ["eu-west-1", "ap-south-1", "sa-east-1"]
}

// main.tf
locals {
  # Combine regions and remove duplicates using toset()
  combined_regions = toset(concat(var.default_regions, var.new_regions))
}

// outputs.tf
output "regions" {
  value       = local.combined_regions
  description = "The combined unique regions from default and new regions"
}

모범 사례

  • 항상 입력을 검증하세요. 적절한 함수와 함께 validation 블록을 사용합니다.
  • 파일 존재 여부를 우아하게 처리하세요. 파일을 읽기 전에 fileexists()를 사용합니다.
  • 계산에는 적절한 숫자 함수를 사용해 정밀도 문제를 방지합니다.
  • 타임스탬프는 일관되게 포맷하여 인프라 전반에 적용합니다.
  • 함수를 효과적으로 결합해 견고한 데이터 변환 파이프라인을 구축합니다.

@piyushsachdeva

Back to Blog

관련 글

더 보기 »

AWS Terraform 라이프사이클 규칙

소개 인프라스트럭처 코드(IaC)는 업데이트, 교체 및 삭제 시 리소스가 어떻게 동작하는지에 대한 완전한 제어가 있을 때 가장 강력합니다. Terr...

S3에 Terraform 상태 저장

S3를 Terraform 백엔드로 구성하기 Terraform은 상태를 S3 버킷에 저장할 수 있습니다. 아래는 S3 백엔드를 설정하는 최소 구성 예시입니다: hcl terrafor...