Skip to content

Room 34

NODE AFFINITY


The Magnetic Fields

  • Node affinity attracts pods to specific nodes based on labels. Anti-affinity pushes them apart.
  • Schedule pods using affinity rules to find the password.

📜 Mission Briefing

  1. Label a worker node: kubectl label node WORKER disk=ssd.
  2. Deploy affinity-pod.yaml - uses requiredDuringSchedulingIgnoredDuringExecution to target disk=ssd nodes.
  3. Verify the pod lands on the labeled node.
  4. Use pod anti-affinity to ensure two pods DON’T co-locate.
  5. The affinity pod logs the password: affinity.

Key Commands
Command Purpose
kubectl label node NODE key=value Label a node
kubectl get nodes --show-labels View node labels
kubectl get pods -o wide See node placement

Node Affinity & Anti-Affinity
apiVersion: v1
kind: Pod
metadata:
  name: ssd-pod
spec:
  affinity:
    nodeAffinity:
      # HARD requirement - must match
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
          - matchExpressions:
              - key: disk
                operator: In
                values: ["ssd", "nvme"]
      # SOFT preference - try to match
      preferredDuringSchedulingIgnoredDuringExecution:
        - weight: 80
          preference:
            matchExpressions:
              - key: zone
                operator: In
                values: ["us-west-1"]
  containers:
    - name: app
      image: busybox
      command: ['sh', '-c', 'echo affinity && sleep 3600']
# Pod anti-affinity: spread pods across nodes
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  template:
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                  - key: app
                    operator: In
                    values: ["web"]
              topologyKey: "kubernetes.io/hostname"  # One per node
# Operators: In, NotIn, Exists, DoesNotExist, Gt, Lt

# nodeSelector (simpler alternative)
spec:
  nodeSelector:
    disk: ssd

# Node affinity vs nodeSelector:
# nodeSelector: simple key=value matching
# nodeAffinity: expressive rules with AND/OR, soft/hard, operators

Hints

Hint 1

kubectl label node <worker-node> disk=ssd
kubectl apply -f affinity-pod.yaml

Hint 2

kubectl get pod ssd-pod -o wide  # Check node assignment
kubectl logs ssd-pod

Hint 3

The password is affinity.


🔓 Unlock Room 35

openssl enc -aes-256-cbc -d -a -pbkdf2 \
        -in ../room_35/README -out ../room_35/README.txt -pass pass:PASSWORD
cat ../room_35/README.txt