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,
]
}
회수 감지 데몬
on_init_script 안에서 호출하는 spot-watcher.sh를 미리 이미지에 포함하거나, 부팅 시 다운로드합니다.
#!/bin/bash
# spot-watcher.sh: 회수 1~2분 전 알림 수신 시 체크포인트 저장
while true; do
HTTP_CODE=$(curl -s -o /tmp/spot_response -w "%{http_code}" \
--unix-socket /run/eci-guest-agent.sock \
http://localhost/vm/metadata?key=spot_termination_time)
if [ "$HTTP_CODE" -eq 200 ]; then
echo "[$(date)] 회수 예정: $(cat /tmp/spot_response): 체크포인트 저장 중"
# 학습 프로세스에 SIGUSR1 → 체크포인트 저장 (앱 측에서 처리)
pkill -SIGUSR1 -f "python.*train.py" || true
sleep 30
# 오브젝트 스토리지로 업로드
aws s3 sync /workspace/checkpoints \
s3://CHECKPOINT_BUCKET/latest \
--endpoint-url https://s3.elice.cloud
break
fi
sleep 5
done
자세한 회수 감지 메커니즘은 스팟 가상머신 운영를 참고하세요.
변수 정의
# variables.tf
variable "vm_password" { description = "VM password (10-256, 3종 이상)"; sensitive = true }
variable "subnet_id" { description = "서브넷 UUID" }
variable "checkpoint_bucket" { description = "오브젝트 스토리지 버킷 이름" }
variable "s3_endpoint" {
description = "오브젝트 스토리지 엔드포인트"
default = "https://s3.elice.cloud"
}
회수 후 재프로비저닝
스팟 가상머신이 회수되면 eci_virtual_machine_allocation 자원만 새로 만들어 다시 실행할 수 있습니다. VM 자원과 디스크는 유지되어 있어 on_init_script가 다시 실행되며 체크포인트 복원이 자동으로 일어납니다.
# 할당 자원만 재생성 (VM과 디스크는 그대로)
terraform apply -replace="eci_virtual_machine_allocation.run"
자원 가용 상태가 부족하면 할당이 다시 실패할 수 있습니다. 포털 인프라 > 리소스 현황 > 스팟 에서 가용 상태를 확인한 뒤 재시도하세요.
자동 재할당을 CI로 돌리기
회수가 자주 발생하는 시간대에는 CI에서 10–30분 주기로 terraform apply -replace=... 를 실행해 학습이 끊기지 않도록 합니다. 회수 알림(이메일)은 알림로 별도 설정.
다음 단계
- 스팟 가상머신 운영: 회수 감지·체크포인트 패턴
- Terraform 치트시트: 자주 쓰는 명령어와 리소스 패턴 모음
- 공식 provider 문서