Terraform 가이드 (Spot 가상머신)
개요
스팟 가상머신은 온디맨드 대비 할인된 가격으로 제공되지만 (할인율은 자원 수급에 따라 변동) 자원 부족 시 회수될 수 있습니다. Terraform으로 스팟 가상머신을 코드로 관리하면 회수 후 재프로비저닝과 체크포인트 자동 복원을 일관되게 운영할 수 있습니다.
스팟 가상머신의 제약
스팟 가격으로 생성하는 가상머신은 다음을 사용할 수 없습니다.
- 항상 켜기(Always On):
always_on = true설정 시SPOT_ALWAYS_ON_NOT_ALLOWED에러 - 재해 복구(DR):
dr = true설정 시SPOT_DR_NOT_ALLOWED에러 - 가상 클러스터: 연결 불가 (단일 가상머신만 지원)
- GPU 인스턴스에만 적용: CPU 전용 인스턴스 타입은 스팟 가격이 제공되지 않음
자세한 동작은 스팟 가상머신 운영를 참고하세요.
Spot 가격으로 가상머신 정의
기본 흐름은 Terraform 개요와 같지만, eci_pricing 데이터 소스의 pricing_type을 "spot" 으로 지정합니다.
# spot_vm.tf
data "eci_instance_type" "h100_1" {
name = "G-NHHS-80" # H100 SXM × 1
}
data "eci_pricing" "spot_pricing" {
name = "G-NHHS-80"
pricing_type = "spot" # ← 스팟 가격
}
data "eci_pricing" "storage_pricing" {
name = "Block Storage"
pricing_type = "ondemand"
}
data "eci_block_storage_image" "ubuntu" {
name = "Ubuntu 24.04 LTS (AI/GPU) (50 GiB)" # GPU 워크로드: CUDA·드라이버 사전 설치
}
resource "eci_virtual_machine" "spot_training" {
name = "spot-training-01"
instance_type_id = data.eci_instance_type.h100_1.id
pricing_id = data.eci_pricing.spot_pricing.id
username = "elice"
password = var.vm_password
# 스팟 제약: 둘 다 반드시 false
always_on = false
dr = false
# 체크포인트 복원 + 학습 재시작
on_init_script = <<-EOT
#!/bin/bash
set -e
# 1) 오브젝트 스토리지에서 최근 체크포인트 복원
aws s3 sync s3://${var.checkpoint_bucket}/latest /workspace/checkpoints \
--endpoint-url ${var.s3_endpoint} || true
# 2) 학습 재시작 (백그라운드)
nohup python /workspace/train.py \
--resume /workspace/checkpoints/latest.pt \
>> /workspace/train.log 2>&1 &
# 3) 회수 감지 데몬 시작
/workspace/spot-watcher.sh &
EOT
tags = { managed-by = "terraform", workload = "spot-training" }
}
resource "eci_block_storage" "boot_disk" {
attached_machine_id = eci_virtual_machine.spot_training.id
name = "spot-training-01-boot"
size_gib = 200
pricing_id = data.eci_pricing.storage_pricing.id
image_id = data.eci_block_storage_image.ubuntu.id
dr = false
tags = { managed-by = "terraform" }
}
resource "eci_network_interface" "ni" {
attached_subnet_id = var.subnet_id
attached_machine_id = eci_virtual_machine.spot_training.id
name = "spot-training-01-ni"
dr = false
tags = { managed-by = "terraform" }
}
resource "eci_virtual_machine_allocation" "run" {
machine_id = eci_virtual_machine.spot_training.id
tags = { managed-by = "terraform" }
depends_on = [
eci_block_storage.boot_disk,
eci_network_interface.ni,
]
}