콘텐츠로 이동

Lab 90 - ACR + AKS Deployment (Terraform)

목표

강사가 사전 생성한 공유 ACR(Azure Container Registry)에 연결된 AKS(Azure Kubernetes Service) 클러스터를 Terraform으로 배포하고, kubectl로 이미지 Pull 및 기본 배포를 검증합니다.


Architecture Diagram

uml diagram


Resources Created

리소스 기본 이름/값 위치
VNet vnet-{prefix} (10.50.0.0/16) Student RG
Subnet snet-aks (10.50.0.0/22) Student RG
AKS Cluster aks-{prefix} — Azure CNI Overlay, System Assigned Identity, Web App Routing Student RG
System Node Pool system — 1 node, Standard_D2s_v3 Student RG
User Node Pool user — 1 node, Standard_D2s_v3 Student RG
Role Assignment AcrPull — AKS kubelet identity → 공유 ACR Student RG
Node Resource Group mc-{resource_group_name} — AKS가 자동 생성 (VMSS, LB, PIP, Disk 등) Azure 자동 생성

Node Resource Group

AKS 클러스터를 생성하면 Azure가 노드 인프라 전용 RG를 별도로 자동 생성합니다. 이 RG에는 노드 VM(VMSS), Load Balancer, Public IP, OS Disk 등이 들어갑니다. Terraform에서 node_resource_group을 명시하면 MC_<rg>_<cluster>_<region> 형식의 기본 이름 대신 깔끔한 이름을 사용할 수 있습니다.
이 Lab에서는 mc-{resource_group_name} 패턴으로 학생 RG에 종속된 고유한 이름을 사용합니다 (예: mc-rg-az104-student01).

Web App Routing (Ingress Controller)

AKS의 Web App Routing add-on을 활성화하면 NGINX 기반 Ingress Controller가 자동으로 배포됩니다.
IngressClass 이름: webapprouting.kubernetes.azure.com
이 Lab에서는 web_app_routing { dns_zone_ids = [] }로 DNS Zone 없이 활성화하고, Lab 91에서 nip.io를 활용해 Ingress host-based routing을 실습합니다.

비용 주의

AKS 노드 VM 2대는 시간당 과금됩니다. AKS 관리 평면(control plane)은 무료이지만, 노드 VM과 디스크 비용이 발생합니다. 실습 후 반드시 terraform destroy로 정리하세요.


Prerequisite

항목 설명
권한 할당된 Resource Group에 Contributor 이상
ACR 접근 강사가 공유 ACR에 대한 AcrPull role assignment 권한을 허용해야 함
도구 Azure CLI, Terraform 1.6+, kubectl 설치
인증 az login 후 올바른 subscription 선택
선행 Lab Lab 00 - Skeleton으로 RG 연결 검증 권장
사전 정보 강사가 알려준 공유 ACR 이름 (예: acrXXXXXX)

Azure Cloud Shell 사용 가능

Terraform apply (Step 1~5)는 로컬 터미널에서 실행해야 하지만, Step 6 이후 (kubectl, az 명령)는 Azure Cloud Shell에서도 실행 가능합니다.
Cloud Shell에는 kubectl, az CLI가 사전 설치되어 있으며, az aks get-credentials로 kubeconfig만 설정하면 바로 사용할 수 있습니다.


Step-by-Step

Terraform 코드 위치: labs/terraform/lab90-aks/

1) Prepare variables

cd labs/terraform/lab90-aks
cp terraform.tfvars.example terraform.tfvars

에디터로 terraform.tfvars를 열고 다음을 설정합니다.

  • resource_group_name (필수) — 강사가 알려준 본인 RG 이름
  • acr_name (필수) — 강사가 알려준 공유 ACR 이름

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"...
- Installing hashicorp/azurerm v4.x.x...

Terraform has been successfully initialized!

4) Plan

terraform plan

terraform plan에서 볼 것

  • 추가될 리소스 수 — 총 5개 : VNet, Subnet, AKS Cluster, User Node Pool, Role Assignment (data source는 카운트 미포함)
  • AKS Cluster — kubernetes_version, network_profile.network_plugin = "azure" (Azure CNI Overlay), web_app_routing 활성화
  • Role Assignment — AKS kubelet identity → 공유 ACR에 AcrPull 권한
  • aks_fqdn — (known after apply) — apply 후 확정됨

5) Apply

terraform apply

프롬프트에 yes를 입력합니다. AKS 클러스터 생성에 5~10분 소요됩니다.

예상 출력 (요약)
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.

Outputs:
acr_login_server    = "acraz104xxxxxx.azurecr.io"
acr_name            = "acraz104xxxxxx"
aks_cluster_name    = "aks-az104-aks"
aks_fqdn            = "az104-aks-xxxxxxxx.hcp.koreacentral.azmk8s.io"
aks_subnet_name     = "snet-aks"
kube_config_command = "az aks get-credentials -g rg-az104-student01 -n aks-az104-aks --overwrite-existing"
location            = "koreacentral"
resource_group_name = "rg-az104-student01"
vnet_name           = "vnet-az104-aks"

6) Get kubeconfig

az aks get-credentials -g "$(terraform output -raw resource_group_name)" -n "$(terraform output -raw aks_cluster_name)" --overwrite-existing
# Cloud Shell에는 Terraform state가 없으므로 직접 입력
RG="<본인 RG 이름>"           # 예: rg-krc-dev-lab90-01
AKS_NAME="<AKS 클러스터 이름>" # 예: aks-az104-aks

az aks get-credentials -g "$RG" -n "$AKS_NAME" --overwrite-existing
for /f "tokens=*" %a in ('terraform output -raw resource_group_name') do set RG=%a
for /f "tokens=*" %a in ('terraform output -raw aks_cluster_name') do set AKS=%a
az aks get-credentials -g "%RG%" -n "%AKS%" --overwrite-existing

Azure Cloud Shell 사용 시

Cloud Shell은 kubectl, az CLI가 사전 설치되어 있어 별도 설치 없이 바로 사용할 수 있습니다.
단, Terraform state가 Cloud Shell에 없으므로 terraform output 명령은 사용할 수 없습니다.
RG 이름과 AKS 이름은 terraform.tfvars 파일 또는 Azure Portal에서 확인하세요.

7) Verify cluster

kubectl get nodes
예상 출력
NAME                              STATUS   ROLES    AGE   VERSION
aks-system-XXXXXXXX-vmssXXXXXX    Ready    <none>   5m    v1.3x.x
aks-user-XXXXXXXX-vmssXXXXXX      Ready    <none>   5m    v1.3x.x

system pool 1노드 + user pool 1노드 = 총 2노드

8) Web App Routing (Ingress Controller) 확인

kubectl get ingressclass
kubectl get pods -n app-routing-system
예상 출력
NAME                                    CONTROLLER                          PARAMETERS   AGE
webapprouting.kubernetes.azure.com      k8s.io/app-routing-system/nginx     <none>       5m

NAME                             READY   STATUS    RESTARTS   AGE
nginx-xxxxxxx-xxxxx              1/1     Running   0          5m

Ingress Controller Ready

app-routing-system namespace에 nginx Pod이 Running이면 Ingress 리소스를 생성할 수 있습니다.
다음 Lab (Lab 91 - AKS App)에서 Ingress를 통해 서비스를 외부 노출합니다.


Verify - Azure Portal

  1. Resource Group → AKS 클러스터, VNet, 관련 리소스가 보이는지 확인합니다.
  2. AKS 클러스터 → Node pools → system (1 node) + user (1 node) 확인합니다.
  3. AKS 클러스터 → Networking → Azure CNI Overlay, VNet/subnet 연결 확인합니다.

Verify - kubectl

기본 nginx 배포 (ACR 없이 빠른 테스트)

kubectl create deployment nginx --image=nginx:latest --replicas=2
kubectl expose deployment nginx --port=80 --type=LoadBalancer

# External IP 할당 대기
kubectl get svc nginx -w

# 접속 테스트
curl http://<EXTERNAL-IP>/

# 정리
kubectl delete svc nginx
kubectl delete deployment nginx

추가 확인 (Portal)

아래 항목을 Portal에서 직접 확인해 보세요:

  • AKS 클러스터 → Overview → Kubernetes version, Provisioning State 확인
  • AKS 클러스터 → Node pools → system / user pool 각각의 노드 수, VM Size, Status 확인
  • AKS 클러스터 → Networking → Network configuration (Azure CNI Overlay, VNet 연결) 확인
  • Container Registry → Access keys 에서 Admin user 설정 확인, Repositories 에서 push된 이미지 목록 확인

Verify - Deep Dive

기본 검증 후 클러스터 내부 상태를 좀 더 깊이 살펴봅니다. 운영 환경에서 노드, Pod, 이벤트를 확인하는 패턴과 동일합니다.

Namespace 전체 파악

kubectl get namespaces
예상 출력
NAME                  STATUS   AGE
app-routing-system    Active   10m
default               Active   10m
kube-node-lease       Active   10m
kube-public           Active   10m
kube-system           Active   10m

app-routing-system은 Web App Routing add-on이 만든 namespace입니다.

Pod 전체 조회

kubectl get pods -A -o wide

-A (all namespaces)와 -o wide(노드 배치 확인)를 함께 쓰면 어떤 Pod이 어느 노드에 있는지 한눈에 볼 수 있습니다.

노드 상세 정보

kubectl describe node <NODE_NAME>
어디를 볼까
  • Conditions — Ready, MemoryPressure, DiskPressure 등 노드 Health
  • Capacity / Allocatable — vCPU, 메모리, Pod 수 한도
  • Non-terminated Pods — 현재 이 노드에 스케줄된 Pod 목록
  • Allocated resources — CPU/Memory requests/limits 합산

리소스 사용량 (Metrics Server)

AKS는 Metrics Server가 기본 설치되어 있어 kubectl top을 바로 쓸 수 있습니다.

kubectl top nodes
kubectl top pods -A
예상 출력 (노드)
NAME                              CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%
aks-system-xxxxxxxx-vmssxxxxxx    120m         6%     1200Mi          45%
aks-user-xxxxxxxx-vmssxxxxxx       80m         4%      800Mi          30%

이벤트 확인 (트러블슈팅 핵심)

kubectl get events -A --sort-by='.lastTimestamp' | tail -20

Pod 생성 실패, 스케줄링 오류, 이미지 Pull 실패 등 대부분의 문제 원인이 Event에 먼저 기록됩니다.

Azure CLI로 클러스터 상태 확인

az aks show -g "$(terraform output -raw resource_group_name)" \
            -n "$(terraform output -raw aks_cluster_name)" \
            -o table
az aks show -g "$RG" -n "$AKS_NAME" -o table
주요 확인 항목
  • ProvisioningState — Succeeded여야 정상
  • PowerState — Running
  • KubernetesVersion — 배포된 K8s 버전

ACR 연결 진단

az aks check-acr -g "$(terraform output -raw resource_group_name)" \
                 -n "$(terraform output -raw aks_cluster_name)" \
                 --acr "$(terraform output -raw acr_login_server)"
az aks check-acr -g "$RG" -n "$AKS_NAME" \
                 --acr "<ACR 로그인 서버>"  # 예: acraz104ktds2026xxxx.azurecr.io

PASSED가 나오면 AKS 노드에서 ACR 이미지를 Pull할 수 있는 상태입니다. ImagePullBackOff 발생 시 이 명령으로 원인을 빠르게 좁힐 수 있습니다.


Cleanup (Teardown)

아직 삭제하지 마세요

이 Lab에서 생성한 AKS 클러스터는 Lab 91 (App Deploy), Lab 92 (Monitoring) 에서 계속 사용합니다.
세 Lab을 모두 완료한 뒤 Custom Lab Cleanup 에서 한꺼번에 삭제합니다.


Terraform Files

파일 역할
versions.tf Terraform / provider 버전 제약
providers.tf azurerm provider
variables.tf prefix, RG, ACR, VM size, 노드 수 등 입력 변수
main.tf RG data source, locals
network.tf VNet, AKS 노드 서브넷
aks.tf AKS 클러스터, user node pool, ACR role assignment
outputs.tf 클러스터 이름, FQDN, kubeconfig 명령, ACR 정보
terraform.tfvars.example 변수 예시 파일

Next Steps

이 Lab에서 AKS 클러스터와 ACR 연결이 완료되었습니다. 다음 Lab에서 이 클러스터 위에 애플리케이션을 배포합니다.

순서 Lab 내용
→ Lab 91 - AKS App Deploy Kustomize 기반 마이크로서비스 배포, Service/Ingress 외부 노출
3 Lab 92 - AKS Monitoring OTel Collector → Azure Monitor, 분산 추적, Alert
4 Custom Lab Cleanup 전체 리소스 역순 삭제

kubectl 컨텍스트 유지

Lab 91·92로 넘어갈 때 터미널을 새로 열었다면 az aks get-credentials 명령(Step 6)을 다시 실행해 kubeconfig를 설정하세요. 같은 터미널이면 그대로 이어서 진행합니다.


Troubleshooting

증상 원인 해결
Resource Group "xxx" was not found RG 이름 오류 또는 다른 subscription terraform.tfvars와 az account show 확인
ContainerRegistryNotFound ACR 이름 오류 또는 다른 RG acr_name, acr_resource_group_name 확인
AuthorizationFailed (role assignment) 공유 ACR에 대한 권한 부족 강사에게 문의 (ACR scope에 role assignment 권한 필요)
AKS 생성 실패 (quota) region별 vCPU 할당량 초과 az vm list-usage -l koreacentral -o table로 확인
AADSTS50132 / Interactive authentication is needed Azure CLI 토큰 만료 az login 후 az account set -s <SUB>, 같은 터미널에서 재시도
kubectl get nodes — NotReady 노드 프로비저닝 중 수 분 대기, kubectl describe node로 Conditions 확인
kubectl get nodes — 연결 실패 kubeconfig 미설정 또는 만료 az aks get-credentials 다시 실행
ImagePullBackOff ACR 이미지 없음 또는 AcrPull 권한 미연결 az aks check-acr로 진단, 이미지 이름·태그 확인
Pod Pending — Insufficient resources 노드 CPU/Memory 부족 kubectl describe pod <NAME>, kubectl top nodes로 여유 확인
kubectl top nodes — error: Metrics API not available Metrics Server 미기동 kubectl get pods -n kube-system -l k8s-app=metrics-server로 확인, 수 분 대기
LoadBalancer Service에 External IP가 <pending> LB PIP 할당 지연 또는 quota kubectl describe svc <NAME>, kubectl get events 확인

Cost & Caution

실수 방지

terraform.tfvars의 resource_group_name이 반드시 본인 RG인지 확인한 뒤 apply하세요. AKS 노드 VM 2대(Standard_D2s_v3)는 실습 시간 외에도 과금되므로, 실습이 끝나면 반드시 terraform destroy하세요.