apiVersion: v1 kind: ServiceAccount metadata: name: spot-handler-sa namespace: default --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: spot-handler-role rules: # Izin untuk cordon node - apiGroups: [""] resources: ["nodes"] verbs: ["get", "patch", "update"] # Izin untuk membaca dan mengevakuasi pod - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "watch"] - apiGroups: [""] resources: ["pods/eviction"] verbs: ["create"] - apiGroups: ["apps"] resources: ["daemonsets"] verbs: ["get"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: spot-handler-binding subjects: - kind: ServiceAccount name: spot-handler-sa namespace: default roleRef: kind: ClusterRole name: spot-handler-role apiGroup: rbac.authorization.k8s.io --- apiVersion: apps/v1 kind: DaemonSet metadata: name: spot-termination-handler namespace: default spec: selector: matchLabels: app: spot-termination-handler template: metadata: labels: app: spot-termination-handler spec: serviceAccountName: spot-handler-sa # Hanya deploy ke node yang memiliki label node-type: spot nodeSelector: node-type: spot containers: - name: handler image: bitnami/kubectl:latest env: # Mengambil nama node tempat pod ini berjalan secara otomatis - name: NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName - name: TRIGGER_FILE value: "/tmp/preempt_signal" command: - "/bin/sh" - "-c" - | echo "[INFO] Spot Termination Handler active on node: $NODE_NAME" echo "[INFO] Listening for termination event..." # Di cloud nyata: curl ke http://169.254.169.254/... (AWS/GCP metadata) # Di lab Kind: kita monitor file trigger /tmp/preempt_signal while true; do if [ -f "$TRIGGER_FILE" ]; then echo "[ALERT] Preemption signal received on $NODE_NAME!" echo "[ACTION] Cordoning node $NODE_NAME..." kubectl cordon "$NODE_NAME" echo "[ACTION] Draining node $NODE_NAME..." kubectl drain "$NODE_NAME" \ --ignore-daemonsets \ --delete-emptydir-data \ --grace-period=30 \ --force echo "[DONE] Node $NODE_NAME safely evacuated. Awaiting cloud teardown." rm -f "$TRIGGER_FILE" break fi sleep 2 done # Jaga container tetap hidup agar log bisa diperiksa sleep 3600