Drift, Self-Heal & Prune
Drift is any difference between the rendered desired state and the live cluster. The reconcile-loop model compared whole objects, which real tools can't do: the API server adds defaults, controllers write status, an HPA changes replicas, a mutating webhook injects a sidecar. If every one of those counted as drift, nothing would ever be Synced. This lesson is about what should count, and how to tell the agent.
Compare only what you own
The live object has far more fields than your manifest:
# in Git # live in the cluster (abridged)
spec: spec:
replicas: 2 replicas: 7 # changed by the HPA
template: revisionHistoryLimit: 10 # API-server default
spec: progressDeadlineSeconds: 600
containers: strategy: {type: RollingUpdate, rollingUpdate: {...}}
- name: linkly template:
image: linkly:1.4.0 spec:
containers:
- name: linkly
image: linkly:1.4.0
imagePullPolicy: IfNotPresent # default
terminationMessagePath: /dev/termination-log
- name: istio-proxy # injected by a webhook
status: ... status: {...} # written by controllersBoth tools ignore defaults and status, by computing the diff as "what would change if I applied my manifest": Flux uses Kubernetes server-side apply in dry-run mode; Argo CD uses a three-way diff with the last-applied state, or server-side diff when you enable it. Fields your manifest never mentions are not drift. That leaves the cases where two writers both set the same field, like replicas here.
A field-level model
def flatten(obj, prefix=""):
"""Turn nested dicts into {"/spec/replicas": 2, ...} (JSON-pointer style paths)."""
out = {}
for key, value in obj.items():
path = f"{prefix}/{key}"
if isinstance(value, dict):
out.update(flatten(value, path))
else:
out[path] = value
return out
def drift(desired, live, ignore=()):
want, have = flatten(desired), flatten(live)
return [f"{p}: {have.get(p)} (Git says {v})"
for p, v in sorted(want.items())
if p not in ignore and have.get(p) != v]
desired = {"spec": {"replicas": 2, "template": {"image": "linkly:1.4.0"}}}
live = {"spec": {"replicas": 7, "revisionHistoryLimit": 10,
"template": {"image": "linkly:1.4.0", "imagePullPolicy": "IfNotPresent"}},
"status": {"readyReplicas": 7}}
print("fields set only by the cluster are ignored; shared fields are compared:")
print(" ", drift(desired, live) or "no drift")
print("ignoring /spec/replicas (the HPA owns it):")
print(" ", drift(desired, live, ignore={"/spec/replicas"}) or "no drift")
live["spec"]["template"]["image"] = "linkly:1.4.0-hotfix" # someone ran kubectl set image
print("after a manual image change:")
print(" ", drift(desired, live, ignore={"/spec/replicas"}) or "no drift")fields set only by the cluster are ignored; shared fields are compared:
['/spec/replicas: 7 (Git says 2)']
ignoring /spec/replicas (the HPA owns it):
no drift
after a manual image change:
['/spec/template/image: linkly:1.4.0-hotfix (Git says linkly:1.4.0)']
Ignoring a field is a decision about ownership: the HPA owns replicas, so Git shouldn't fight it, while the image is owned by Git, so a manual change is real drift.
The simplest fix: don't set the field
If an HPA manages a Deployment, leave replicas out of the manifest (in a chart: {{- if not .Values.autoscaling.enabled }} replicas: … {{- end }}, as the helm-kustomize chart does). Then nobody else claims the field. Use explicit ignore rules only for fields you can't remove from the source.
Telling each tool to ignore a field
Argo CD: ignoreDifferences on the Application, plus RespectIgnoreDifferences=true so that a sync doesn't overwrite the ignored field either (without it, ignored fields are hidden from the diff but still applied when something else triggers a sync). Flux's helm-controller has its own drift detection, which is off by default and accepts ignore rules; kustomize-controller always corrects drift on the fields the manifest sets. The session validates both against their CRD schemas:
cat > argo.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata: {name: linkly-production, namespace: argocd}
spec:
project: linkly
source:
repoURL: https://github.com/acme/linkly-deploy.git
targetRevision: main
path: charts/linkly
helm: {valueFiles: [../../apps/linkly/production/values.yaml]}
destination: {server: https://kubernetes.default.svc, namespace: linkly-prod}
ignoreDifferences:
- group: apps
kind: Deployment
jsonPointers: [/spec/replicas]
syncPolicy:
automated: {prune: true, selfHeal: true}
syncOptions: [RespectIgnoreDifferences=true]
EOF
cat > flux.yaml <<'EOF'
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata: {name: linkly, namespace: linkly-prod}
spec:
interval: 10m
chartRef: {kind: OCIRepository, name: linkly-chart}
driftDetection:
mode: enabled # warn = only report, disabled = the default
ignore:
- paths: [/spec/replicas]
target: {kind: Deployment}
EOF
kubeconform -strict -summary argo.yaml flux.yamlSummary: 2 resources found in 2 files - Valid: 2, Invalid: 0, Errors: 0, Skipped: 0
Prune: deleting what Git no longer has
Removing a file from Git should remove the object, otherwise the cluster collects orphans: old CronJobs still running, Services still routing, ConfigMaps nobody reads. Both tools can prune, but treat it with respect:
- Argo CD:
syncPolicy.automated.prune: true(off by default, even with auto-sync). Protect individual objects with the annotationargocd.argoproj.io/sync-options: Prune=false.PruneLast=truedeletes only after the other resources are applied and healthy. - Flux:
spec.prune: trueon a Kustomization (theflux create kustomizationdefault). Protect an object with the label or annotationkustomize.toolkit.fluxcd.io/prune: disabled. - Namespaces and PVCs deserve protection: pruning a Namespace deletes everything in it, and pruning a PVC can delete its data (depending on the StorageClass's reclaim policy).
Argo CD also refuses to auto-sync to an empty render unless allowEmpty: true is set: a broken path or a mistaken deletion of the whole folder would otherwise prune the entire application.
Self-heal and the "who changed it?" question
With self-heal on, a manual change lives for seconds (Argo CD waits --self-heal-timeout-seconds, 5 s by default, before re-syncing). That is the point: production changes go through Git. During an incident you may still need a manual change; pause the agent first (argocd app set linkly-production --sync-policy none or flux suspend helmrelease linkly), make the change, then put it in Git and resume. The Field Notes have the full break-glass routine.
Test yourself
An HPA scales linkly to 7 replicas, and the manifest in Git says replicas: 2. What is the cleanest fix?
- Turn off self-heal
- Remove
replicasfrom the manifest when autoscaling is enabled, so only the HPA sets it - Set the HPA's minReplicas to 2
- Run kubectl scale after each sync
Why doesn't imagePullPolicy: IfNotPresent, added by the API server, show up as drift?
- Argo CD and Flux compare only the fields the desired manifest sets (dry-run apply / three-way diff)
- Defaults are stored in Git automatically
- Pull policies are ignored by Kubernetes
- It does show up as drift
In Argo CD, what protects one critical object from automated pruning?
- A finalizer
- The annotation
argocd.argoproj.io/sync-options: Prune=false - Putting it in another namespace
selfHeal: false