Lab 08 - Manage Virtual Machines (Terraform)¶
목표
공식 Lab 08 - Manage Virtual Machines에서 다루는 VM 배포, 가용성 영역, Managed Disk, VM Extension 개념을 Terraform으로 배포하고, Portal / CLI / SSH로 검증합니다.
Architecture Diagram¶
Resources Created¶
| 리소스 | 기본 이름/값 |
|---|---|
| VNet | vnet-{prefix} (10.40.0.0/16) |
| Subnet | snet-workload (10.40.0.0/24) |
| NSG | nsg-{prefix} - SSH(22) + HTTP(80) 허용 |
| Public IP | pip-{prefix} (Standard, Zonal) |
| VM | vm-{prefix} - Ubuntu 24.04, Zone 1, password auth |
| OS Disk | osdisk-{prefix} (Standard LRS) |
| Data Disk | disk-data-{prefix} (Standard LRS, 32 GiB) |
| VM Extension | Custom Script - nginx 설치 + data disk 포맷/마운트 |
비용 주의
VM과 Public IP는 시간당 과금됩니다. 실습이 끝나면 반드시 terraform destroy로 정리하세요.
Prerequisite¶
| 항목 | 설명 |
|---|---|
| 권한 | 할당된 Resource Group에 Contributor 이상 |
| 도구 | Azure CLI 설치, Terraform 1.6+ 설치 |
| 인증 | az login 후 올바른 subscription 선택 |
| 선행 Lab | Lab 00 - Skeleton으로 RG 연결 검증 권장 |
Concept Mapping (Official Lab 08)¶
| 공식 Lab 08 주제 | 이 모듈에서의 위치 |
|---|---|
| VM 배포 (가용성 영역) | vm.tf - azurerm_linux_virtual_machine (zone 설정) |
| Managed Disk (데이터 디스크) | vm.tf - azurerm_managed_disk + attachment |
| VM Extension (Custom Script) | vm.tf - azurerm_virtual_machine_extension, scripts/setup.sh |
| 네트워크 (NSG, Public IP) | network.tf - NSG rules (SSH, HTTP), vm.tf - Standard Public IP |
| VMSS (Scale Set) | 본 모듈 범위 밖 - 별도 설명 |
custom_data vs Custom Script Extension¶
VM에 소프트웨어를 설치하는 방법은 크게 두 가지입니다.
| 항목 | custom_data (cloud-init) |
Custom Script Extension |
|---|---|---|
| 실행 시점 | VM 첫 부팅 시 1회 | VM 생성 후 별도 리소스로 실행 |
| 재실행 | VM을 재생성해야 재실행 | Extension 리소스만 업데이트하면 재실행 가능 |
| Terraform 리소스 | azurerm_linux_virtual_machine의 custom_data 속성 |
azurerm_virtual_machine_extension (별도 리소스) |
| 의존성 제어 | VM 내부에서 순서 보장 어려움 | depends_on으로 디스크 attach 등 선행 작업 보장 |
| 스크립트 크기 | base64 인코딩 후 64 KB 제한 | Blob Storage 참조 시 사실상 무제한 |
| 사용 예 | 패키지 설치, 설정 파일 생성 등 간단한 초기화 | 디스크 포맷, 복잡한 설치, 외부 파일 다운로드 |
이 Lab에서의 선택
Lab 08에서는 Data Disk가 attach된 이후에 포맷/마운트해야 하므로 custom_data로는 타이밍을 보장할 수 없습니다.
따라서 depends_on = [azurerm_virtual_machine_data_disk_attachment.data]를 걸 수 있는 Custom Script Extension을 사용합니다.
반면 Lab 06에서는 디스크가 없고 nginx + index.html 생성만 하면 되므로 간단하게 custom_data를 사용합니다.
Step-by-Step¶
Terraform 코드 위치: labs/terraform/lab08-manage-vms/
1) Prepare variables¶
cd labs/terraform/lab08-manage-vms
cp terraform.tfvars.example terraform.tfvars
에디터로 terraform.tfvars를 열고 다음을 설정합니다.
resource_group_name(필수) — 강사가 알려준 본인 RG 이름availability_zone(선택) — region이 가용성 영역을 지원하지 않으면""(빈 문자열)로 설정
2) Login to Azure¶
az login
az account show -o table
3) Initialize Terraform¶
terraform init
예상 출력
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/azurerm versions matching "~> 4.0"...
- Finding hashicorp/random versions matching "~> 3.6"...
- Installing hashicorp/azurerm v4.x.x...
- Installing hashicorp/random v3.x.x...
Terraform has been successfully initialized!
4) Plan¶
terraform plan
terraform plan에서 볼 것
- 추가될 리소스 수 — VNet, Subnet, NSG, NSG Rule x2, subnet-NSG association, Public IP, NIC, VM, Managed Disk, Disk Attachment, VM Extension, random_password 총 13개
random_password— VM 비밀번호가 새로 생성되는지 (재적용 시 변경될 수 있음)vm_public_ip—(known after apply)로 표시되며, apply 후 확정됨protected_settings— Custom Script Extension의 스크립트 내용은 민감 정보로 마스킹됨
5) Apply¶
terraform apply
프롬프트에 yes를 입력합니다. 완료까지 수 분 소요됩니다(VM 프로비저닝 + Extension 실행).
예상 출력 (요약)
Apply complete! Resources: 13 added, 0 changed, 0 destroyed.
Outputs:
admin_password = <sensitive>
admin_username = "azureuser"
data_disk_name = "disk-data-az104-lab08"
location = "koreacentral"
nsg_name = "nsg-az104-lab08"
resource_group_name = "rg-az104-student01"
vm_name = "vm-az104-lab08"
vm_private_ip = "10.40.0.x"
vm_public_ip = "x.x.x.x"
vnet_name = "vnet-az104-lab08"
6) Check outputs¶
terraform output
terraform output vm_public_ip
terraform output admin_username
terraform output -raw admin_password
보안
비밀번호는 터미널 기록이나 스크린샷에 남기지 마세요.
Verify - Azure Portal¶
- Resource Group 이동 → VM, Disk, VNet, NSG, Public IP 등이 보이는지 확인합니다.
- VM 리소스 → Overview에서 Zone, Size, OS 정보를 확인합니다.
- VM → Disks 탭에서 OS disk과 Data disk(
disk-data-{prefix}, 32 GiB)가 보이는지 확인합니다. - VM → Extensions + applications에서
setup(CustomScript)이 Provisioning succeeded인지 확인합니다.
Verify - SSH¶
Public IP로 직접 SSH 접속합니다. 먼저 Public IP를 확인합니다.
terraform output vm_public_ip
ssh azureuser@$(terraform output -raw vm_public_ip)
for /f "tokens=*" %a in ('terraform output -raw vm_public_ip') do ssh azureuser@%a
Cloud Shell에서는 terraform output 을 사용할 수 없으므로, 위에서 확인한 Public IP를 직접 입력합니다.
ssh azureuser@<VM_PUBLIC_IP>
<VM_PUBLIC_IP>를 실제 IP 주소로 바꿔 입력하세요 (예: ssh azureuser@20.39.x.x).
비밀번호 입력 후 접속합니다.
nginx 확인¶
curl -s http://localhost/
# 예상: <h1>Lab 08 - vm-az104-lab08</h1><p>Data disk mounted at /mnt/data</p>
Data Disk 마운트 확인¶
df -h /mnt/data
# 예상: /dev/sdc1 가 /mnt/data 에 마운트됨
ls -la /mnt/data/
외부에서 HTTP 확인¶
로컬 터미널에서:
curl -s http://$(terraform output -raw vm_public_ip)/
for /f "tokens=*" %a in ('terraform output -raw vm_public_ip') do curl -s http://%a/
NSG에서 80 포트가 허용되어 있으므로 nginx 페이지가 응답됩니다.
추가 확인 (Portal)
아래 항목을 Portal에서 직접 확인해 보세요:
- VM → Overview → Status가
Running인지 확인 - VM → Disks → Data disk(
disk-data-{prefix})가 Attached 상태인지, 크기(32 GiB) 확인 - VM → Extensions + applications →
setup(CustomScript)이 Provisioning succeeded 인지 확인 - NSG → Inbound security rules 에서 SSH(22), HTTP(80) 허용 규칙 확인
Cleanup (Teardown)¶
terraform destroy
프롬프트에 yes를 입력합니다.
비용 방지
VM과 Public IP는 시간당 과금됩니다. 실습이 끝나면 반드시 terraform destroy를 실행하세요.
Terraform Files¶
| 파일 | 역할 |
|---|---|
versions.tf |
Terraform / provider 버전 제약 |
providers.tf |
azurerm provider, random provider |
variables.tf |
prefix, RG, VM size, zone, disk size 등 |
main.tf |
RG data source, random_password, locals |
network.tf |
VNet, Subnet, NSG, NSG rules |
vm.tf |
VM, PIP, NIC, Data Disk, Disk Attachment, Custom Script Extension |
outputs.tf |
VM name, IPs, credentials, disk, NSG info |
terraform.tfvars.example |
변수 예시 파일 (비밀 값 없음) |
scripts/setup.sh |
Custom Script: data disk 포맷/마운트 + nginx 설치 |
Troubleshooting¶
| 증상 | 원인 | 해결 |
|---|---|---|
Resource Group "xxx" was not found |
RG 이름 오류 또는 다른 subscription | terraform.tfvars와 az account show 확인 |
| VM Extension 실패 | 스크립트 에러 또는 네트워크 문제 | Portal → VM → Extensions에서 상세 로그 확인 |
| SSH 접속 불가 | NSG 규칙 미적용 또는 Public IP 미할당 | az network nsg rule list와 terraform output vm_public_ip 확인 |
| Data Disk 미인식 | Disk attachment 순서 문제 | lsblk로 디바이스 확인, depends_on 적용됨 |
| Zone 에러 | Region이 가용성 영역 미지원 | availability_zone = "" 로 설정 |
Cost & Caution¶
실수 방지
terraform.tfvars의 resource_group_name이 반드시 본인 RG인지 확인한 뒤 apply하세요. Public IP가 있는 VM은 SSH 공격 대상이 될 수 있으므로, 실습 외 시간에는 VM을 중지하거나 terraform destroy하세요.