## Intro

Pod affinity and anti-affinity rules in Kubernetes control where pods are scheduled relative to other pods and to node labels. These rules directly affect application resilience: they help keep replicas on separate failure domains, co-locate services that need low latency, or pin workloads to specialized hardware. Because they are usually embedded inside Deployment, StatefulSet, or Pod specs, a small misconfiguration or accidental deletion can silently break scheduling and cause an outage hours later.

Backing up and restoring these rules is not just about saving YAML files. It requires knowing which workloads use affinity, documenting the node labels those rules depend on, testing that restored rules still schedule pods, and having a rollback plan when a restore goes wrong. This guide walks through a complete operational workflow: inventorying affinity rules, creating version-controlled backups, restoring them safely with kubectl, verifying scheduling after restore, diagnosing common failures, and maintaining a repeatable operations checklist. Every step includes concrete commands and expected output so you can follow along on your own cluster.

## Version and Environment Inventory

Before you touch any affinity rule, you need a clear picture of your cluster. Kubernetes version matters because affinity features have evolved: `matchLabelKeys` and `mismatchLabelKeys` arrived in 1.21 (alpha) and stabilized later, while `namespaceSelector` has been stable since 1.6. Node labels are equally critical because affinity rules reference topology keys like `topology.kubernetes.io/zone` or custom keys like `disktype=ssd`. If those labels are missing on the target cluster, restored pods will never schedule.

Start with a small inventory of your environment.

### Step 1: Check Kubernetes Version

Run the server version check first:

```bash
kubectl version --short
```

Expected output (example):

```
Client Version: v1.23.5
Server Version: v1.23.5
```

Note the server version. If you use advanced fields like `matchLabelKeys`, confirm they are enabled in your distribution. For example, in Kubernetes 1.22, `matchLabelKeys` is alpha and requires the `PodAffinityNamespaceSelector` feature gate. When you plan a restore, the target cluster must be at least as new as the source for those fields to be accepted.

### Step 2: Identify Namespaces and Workloads with Affinity Rules

Affinity rules can appear in Deployments, StatefulSets, DaemonSets, Jobs, and standalone Pods. List all of them across your cluster or within a pilot namespace.

For Deployments in a specific namespace:

```bash
kubectl get deployments -n my-namespace -o json | jq -r '.items[] | select(.spec.template.spec.affinity != null) | .metadata.name'
```

Expected output:

```
web-app
backend-service
```

Repeat for other resource types:

```bash
kubectl get statefulsets -n my-namespace -o json | jq -r '.items[] | select(.spec.template.spec.affinity != null) | .metadata.name'
kubectl get daemonsets -n my-namespace -o json | jq -r '.items[] | select(.spec.template.spec.affinity != null) | .metadata.name'
kubectl get jobs -n my-namespace -o json | jq -r '.items[] | select(.spec.template.spec.affinity != null) | .metadata.name'
```

For standalone Pods, the path is `spec.affinity` instead of `spec.template.spec.affinity`:

```bash
kubectl get pods -n my-namespace -o json | jq -r '.items[] | select(.spec.affinity != null) | .metadata.name'
```

Keep this list in a text file or spreadsheet. It becomes your inventory of workloads that need affinity backups.

### Step 3: Document Node Labels and Topology

Affinity rules reference node labels through `topologyKey` or `nodeSelectorTerms`. For example, a pod anti-affinity rule might use `topologyKey: kubernetes.io/hostname` to spread replicas across physical nodes, or `topologyKey: topology.kubernetes.io/zone` to spread across availability zones. A pod affinity rule might use a custom label like `disktype=ssd` to co-locate with a stateful service.

List all node labels:

```bash
kubectl get nodes --show-labels
```

Example output:

```
NAME    STATUS   ROLES    AGE   VERSION   LABELS
node-1  Ready    <none>   10d   v1.23.5   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node-1,topology.kubernetes.io/region=us-east-1,topology.kubernetes.io/zone=us-east-1a,disktype=ssd
node-2  Ready    <none>   10d   v1.23.5   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node-2,topology.kubernetes.io/region=us-east-1,topology.kubernetes.io/zone=us-east-1b,disktype=ssd
```

Save this output. Cross-reference the labels used in your affinity rules. If any `topologyKey` or selector key does not appear on any node in the target cluster, pods will fail to schedule after restore. This is one of the most common failure modes, so document it now.

### Step 4: Capture Current Affinity Definitions

For each workload from Step 2, extract the full affinity block and save it in a structured backup directory. First, get the complete workload YAML for reference:

```bash
kubectl get deployment web-app -n my-namespace -o yaml > web-app-deployment.yaml
```

Then extract just the affinity section to a separate file. Use `jq` to pull the JSON and `yq` to convert to YAML:

```bash
kubectl get deployment web-app -n my-namespace -o json | jq '.spec.template.spec.affinity' | yq -P > web-app-affinity.yaml
```

Example content of `web-app-affinity.yaml`:

```yaml
podAntiAffinity:
  requiredDuringSchedulingIgnoredDuringExecution:
    - labelSelector:
        matchExpressions:
          - key: app
            operator: In
            values:
              - web
      topologyKey: kubernetes.io/hostname
```

Store these files in a version-controlled repository with this structure:

```
affinity-backup/
├── my-namespace/
│   ├── deployment-web-app-affinity.yaml
│   ├── deployment-backend-service-affinity.yaml
│   └── pod-standalone-affinity.yaml
└── other-namespace/
    └── statefulset-db-affinity.yaml
```

Commit to Git. This gives you an audit trail and a restore source.

### Inventory Checklist

| Item | Command | Expectation |
|------|---------|-------------|
| Kubernetes version | `kubectl version --short` | Same or compatible version on restore target |
| Workloads with affinity | `kubectl get deployments,statefulsets,daemonsets,jobs,pods -A -o json \| jq ...` | List of resources with `spec.template.spec.affinity` or `spec.affinity` |
| Node labels | `kubectl get nodes --show-labels` | All labels used in affinity rules present |
| Affinity definitions | `kubectl get <resource> <name> -n <ns> -o yaml` | Full YAML with affinity block |

## Safe Configuration Path

Restoring affinity rules can cause rolling updates and rescheduling. A disciplined approach avoids surprises. This section describes a surgical restore method using `kubectl patch`, which modifies only the affinity field without touching other spec sections.

### Step 1: Define Backup Scope

Start with a pilot namespace or a few workloads that have well-understood affinity rules. For this guide, we use namespace `my-namespace` and workloads `web-app` and `backend-service`.

### Step 2: Create Backup Files

For each workload, run the extraction command shown earlier. Save the output into the directory structure. For example:

```bash
mkdir -p affinity-backup/my-namespace
kubectl get deployment web-app -n my-namespace -o json | jq '.spec.template.spec.affinity' | yq -P > affinity-backup/my-namespace/deployment-web-app-affinity.yaml
kubectl get deployment backend-service -n my-namespace -o json | jq '.spec.template.spec.affinity' | yq -P > affinity-backup/my-namespace/deployment-backend-service-affinity.yaml
```

If a workload has no affinity, the file will contain `null`. You can skip those by checking first:

```bash
if kubectl get deployment web-app -n my-namespace -o json | jq -e '.spec.template.spec.affinity != null' > /dev/null; then
  kubectl get deployment web-app -n my-namespace -o json | jq '.spec.template.spec.affinity' | yq -P > affinity-backup/my-namespace/deployment-web-app-affinity.yaml
fi
```

### Step 3: Restore Procedure Using Kubectl Patch

To restore the affinity from the backup file, use `kubectl patch` with `--type merge` and `--patch-file`. This replaces the entire `affinity` field with the contents of the file. It does not touch other fields like image or replicas.

```bash
kubectl patch deployment web-app -n my-namespace --type merge --patch-file affinity-backup/my-namespace/deployment-web-app-affinity.yaml
```

Expected output:

```
deployment.apps/web-app patched
```

If the backup file contains the affinity under a different path (e.g., it was extracted as just the affinity object), the patch command assumes the file content is a valid strategic merge patch. Because we extracted `.spec.template.spec.affinity`, the file starts with `podAntiAffinity:` or `podAffinity:`. The merge patch expects the full path from the root, so you need to wrap the content. To avoid that, create a wrapper file:

```bash
cat > web-app-affinity-patch.yaml <<EOF
spec:
  template:
    spec:
      affinity:
$(sed 's/^/        /' affinity-backup/my-namespace/deployment-web-app-affinity.yaml)
EOF
```

Then apply:

```bash
kubectl patch deployment web-app -n my-namespace --type merge --patch-file web-app-affinity-patch.yaml
```

Alternatively, use `jq` to build the patch from the backup JSON:

```bash
kubectl patch deployment web-app -n my-namespace --type merge -p "$(jq -n --argjson aff "$(cat affinity-backup/my-namespace/deployment-web-app-affinity.json 2>/dev/null || kubectl get deployment web-app -n my-namespace -o json | jq '.spec.template.spec.affinity')" '{spec: {template: {spec: {affinity: $aff}}}}')"
```

For simpler cases, you can keep the backup in JSON and use `kubectl patch` with a JSON patch:

```bash
kubectl patch deployment web-app -n my-namespace --type json -p '[{"op": "replace", "path": "/spec/template/spec/affinity", "value": <backup JSON>}]'
```

But the merge patch with a file is easiest for humans to review.

### Step 4: Scoped Implementation Choices

When you patch a Deployment's affinity, Kubernetes performs a rolling update: old pods are gradually replaced by new pods that must satisfy the new affinity. If the new rules are too restrictive or reference missing labels, the rollout will stall. Before patching in production, test in a staging namespace or cluster.

Consider these choices:

- **Patch vs. full apply**: `kubectl patch` changes only the affinity field. `kubectl apply -f full-manifest.yaml` can inadvertently overwrite other fields if your local manifest is outdated. Use patch for surgical changes.
- **Rollout pause**: If you need to monitor the change, pause the rollout before patching and resume after verification:

```bash
kubectl rollout pause deployment web-app -n my-namespace
kubectl patch deployment web-app -n my-namespace --type merge --patch-file web-app-affinity-patch.yaml
kubectl rollout resume deployment web-app -n my-namespace
```

- **Namespace isolation**: Keep a separate test namespace with the same node labels to validate scheduling without affecting production.

### Code Example: Backup and Restore Script

Here is a reusable script to back up all affinity definitions in a namespace. It loops through Deployments, StatefulSets, DaemonSets, and Jobs, extracts the affinity, and saves the YAML.

```bash
#!/bin/bash
# backup-affinity.sh <namespace>
NS=$1
BACKUP_DIR="affinity-backup/$NS"
mkdir -p "$BACKUP_DIR"

for type in deployment statefulset daemonset job; do
  kubectl get $type -n "$NS" -o json | jq -r '.items[] | select(.spec.template.spec.affinity != null) | .metadata.name' | while read name; do
    if [ -n "$name" ]; then
      kubectl get $type "$name" -n "$NS" -o json | jq '.spec.template.spec.affinity' | yq -P > "$BACKUP_DIR/${type}-${name}-affinity.yaml"
      echo "Backed up $type/$name affinity"
    fi
  done
done

# For standalone Pods
kubectl get pods -n "$NS" -o json | jq -r '.items[] | select(.spec.affinity != null) | .metadata.name' | while read name; do
  if [ -n "$name" ]; then
    kubectl get pod "$name" -n "$NS" -o json | jq '.spec.affinity' | yq -P > "$BACKUP_DIR/pod-${name}-affinity.yaml"
    echo "Backed up pod/$name affinity"
  fi
done
```

Run it:

```bash
./backup-affinity.sh my-namespace
```

Expected output:

```
Backed up deployment/web-app affinity
Backed up deployment/backend-service affinity
```

## Verification and Diagnostics

After restoring affinity rules, verify that the live spec matches the backup and that pods schedule correctly. This section covers observable checks with expected results.

### Step 1: Confirm the Affinity Configuration in the Workload Spec

Check the current affinity on the workload:

```bash
kubectl get deployment web-app -n my-namespace -o jsonpath='{.spec.template.spec.affinity}' | jq .
```

Compare this output with the backup file. They should match exactly.

### Step 2: Check for Pending Pods and Events

Affinity rules can cause pods to remain Pending if no node satisfies them. List pods and watch for status:

```bash
kubectl get pods -n my-namespace -l app=web -w
```

If pods stay Pending, describe one to see the reason:

```bash
kubectl describe pod <pod-name> -n my-namespace
```

Look for events like:

```
Events:
  Type     Reason            Age   From               Message
  ----     ------            ----  ----               -------
  Warning  FailedScheduling  2m    default-scheduler  0/3 nodes are available: 3 node(s) didn't match pod anti-affinity rules.
```

This indicates the anti-affinity rule is too restrictive or references missing topology labels.

### Step 3: Validate Scheduling After a Rolling Update

Trigger a rolling update to ensure new pods are scheduled according to the restored affinity:

```bash
kubectl rollout restart deployment web-app -n my-namespace
```

Watch the rollout status:

```bash
kubectl rollout status deployment web-app -n my-namespace
```

Expected output:

```
Waiting for deployment "web-app" rollout to finish: 0 of 2 updated replicas are available...
deployment "web-app" successfully rolled out
```

If the rollout fails or takes too long, inspect events and pod distribution.

### Step 4: Check Node Labels and Topology Availability

Ensure the topology keys used in affinity rules exist on nodes:

```bash
kubectl get nodes --show-labels | grep topology.kubernetes.io/zone
```

If a topology key is missing, add it to nodes before applying the affinity. For a pilot, you can test scheduling feasibility by creating a temporary pod with the same labels and affinity in a test namespace, but that requires matching node labels.

### Verification Steps and Expected Outcomes

| Verification Step | Command | Success Criterion |
|-------------------|---------|-------------------|
| Affinity in spec | `kubectl get deployment web-app -n my-namespace -o jsonpath='{.spec.template.spec.affinity}'` | Output matches backup |
| Pods scheduled | `kubectl get pods -n my-namespace -l app=web` | All pods Running, not Pending |
| Rollout success | `kubectl rollout status deployment web-app -n my-namespace` | "successfully rolled out" |
| Node labels match | `kubectl get nodes --show-labels` | Topology keys used in affinity exist |

## Common Pitfalls and Failure Modes

Restoring affinity rules can go wrong in predictable ways. Understanding these pitfalls prevents hours of debugging.

### Topology Key Mismatch

**What happens**: The restored affinity references a `topologyKey` like `topology.kubernetes.io/zone`, but the target cluster does not have that label on nodes, or the label values differ from the source cluster.

**Why it happens**: Clusters are often created with different node labeling schemes. For example, a managed cluster may not include cloud provider topology labels unless configured.

**How to avoid**: Before restore, run `kubectl get nodes --show-labels` and compare the labels with the topology keys in your backup. If a key is missing, either add it to nodes or modify the affinity rule to use a label that exists.

**How to recover**: Either patch nodes with the missing label:

```bash
kubectl label nodes <node-name> topology.kubernetes.io/zone=us-east-1a
```

Or update the affinity to use a correct key:

```bash
kubectl patch deployment web-app -n my-namespace --type merge -p '{"spec":{"template":{"spec":{"affinity":{"podAntiAffinity":{"requiredDuringSchedulingIgnoredDuringExecution":[{"topologyKey":"kubernetes.io/hostname"}]}}}}}}'
```

### Conflicting Affinity and Anti-Affinity Rules

**What happens**: The workload has both pod affinity and anti-affinity rules that cannot be satisfied simultaneously. For example, affinity to pods with label `app=web` and anti-affinity to the same label on the same topology key.

**Why it happens**: A manual edit or a restore from an inconsistent backup can combine rules that were never tested together.

**How to avoid**: After any change, run a `kubectl apply --dry-run=server` to validate the manifest is accepted, and then test in a staging namespace with a small replica count.

**How to recover**: Remove one of the conflicting rules via patch. For instance, to remove the affinity entirely:

```bash
kubectl patch deployment web-app -n my-namespace --type merge -p '{"spec":{"template":{"spec":{"affinity":null}}}}'
```

### Overly Restrictive Anti-Affinity

**What happens**: You restore a hard anti-affinity rule with `requiredDuringSchedulingIgnoredDuringExecution` and a `topologyKey` that has too few distinct values. For example, 5 replicas spread across only 3 nodes with `topologyKey: kubernetes.io/hostname`: 2 pods cannot schedule.

**Why it happens**: The original cluster had more nodes or fewer replicas. The target cluster is smaller or has fewer distinct topology values.

**How to avoid**: Before restoring, calculate the maximum number of pods per topology value allowed by the anti-affinity rule. If replicas exceed that, adjust replicas or change to `preferredDuringSchedulingIgnoredDuringExecution`.

**How to recover**: Reduce replicas:

```bash
kubectl scale deployment web-app --replicas=3 -n my-namespace
```

Or add more nodes with distinct values for the topology key. Check if any pods remain pending after scaling.

### Label Selector Mismatch

**What happens**: The restored affinity uses label selectors that no longer match any pods or nodes. For example, the backup is from before the team changed app labels from `app=web` to `app=frontend`.

**Why it happens**: Labels evolve over time, and backups taken earlier may not reflect current label conventions.

**How to avoid**: Keep affinity backups in sync with label changes. Before restore, verify that the selector keys and values exist on the intended pods or nodes.

**How to recover**: Update the selector in the affinity rule to match current labels:

```bash
kubectl patch deployment web-app -n my-namespace --type merge -p '{"spec":{"template":{"spec":{"affinity":{"podAntiAffinity":{"requiredDuringSchedulingIgnoredDuringExecution":[{"labelSelector":{"matchLabels":{"app":"frontend"}},"topologyKey":"kubernetes.io/hostname"}]}}}}}}'
```

### Ignoring Rollout Side Effects

**What happens**: You patch a Deployment's affinity and unexpectedly trigger a rolling update that disrupts traffic or cascades failures.

**Why it happens**: Any change to the Pod template in a Deployment triggers a rollout. Teams often forget that affinity is part of the template.

**How to avoid**: Use `kubectl rollout pause` before patching, then resume after verifying in a canary or staging environment. Monitor `kubectl rollout status` to catch issues early.

**How to recover**: If the rollout is failing, use `kubectl rollout undo deployment web-app -n my-namespace` to revert to the previous revision.

### Rollback Procedure

Before any restore, save the current affinity as a pre-change backup:

```bash
kubectl get deployment web-app -n my-namespace -o json | jq '.spec.template.spec.affinity' | yq -P > web-app-affinity-pre-change.yaml
```

If the restore causes issues, roll back by applying the pre-change file with patch. For Deployments, you can also use `kubectl rollout undo`:

```bash
kubectl rollout undo deployment/web-app -n my-namespace
```

Check rollout status:

```bash
kubectl rollout status deployment/web-app -n my-namespace
```

After rollback, verify pod distribution:

```bash
kubectl get pods -n my-namespace -o wide
```

Check the NODE column to confirm pods are on expected nodes.

## Operations Checklist

Use this repeatable checklist to keep affinity backups and restores under control. Assign a single owner for each task to ensure accountability.

| Task | Frequency | Owner | Command/Procedure |
|------|-----------|-------|-------------------|
| Inventory workloads with affinity | Monthly or after changes | Platform Engineer (e.g., Alex Chen) | Use script to list resources with `affinity` field |
| Backup affinity definitions | After any affinity change or before cluster upgrades | DevOps Engineer (e.g., Maria Lopez) | Run `./backup-affinity.sh <namespace>` |
| Verify backup files in version control | Weekly | Tech Lead (e.g., Priya Shah) | Check Git repository for latest commit |
| Validate backup integrity | Quarterly | QA Engineer (e.g., David Kim) | Restore to a test namespace and confirm schedulability |
| Review node label changes | Before applying any node label changes | Cluster Admin (e.g., Sarah Johnson) | `kubectl get nodes --show-labels` and compare to affinity topology keys |
| Document restoration procedure | Continuously | Platform Engineer | Keep runbook updated with steps from this guide |
| Test disaster recovery | Annually or after major cluster changes | SRE Lead (e.g., Tom Wilson) | Perform restore drill in a sandbox cluster |

Each owner is responsible for executing the task and reporting results in the team's operational review (e.g., weekly standup for backups, monthly ops review for integrity checks).

## Conclusion

Backing up and restoring Kubernetes pod affinity and anti-affinity rules is a critical practice for maintaining application resilience. This guide walked through inventory, backup, restore, verification, failure recovery, and an operational checklist with concrete commands and examples. By following these steps, you can preserve your scheduling rules, recover them quickly after an incident, and avoid configuration drift. Start with a small pilot namespace, validate the process thoroughly, and then extend it to all namespaces. Remember to assign clear ownership for each task and test restores regularly to keep your disaster recovery plan effective.