TExcelTAD
Home › GitOps: Argo CD & Flux › Drift, Self-Heal & Prune

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:

yaml
# 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 controllers

Both 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

python · try it yourself
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:

bash · try it yourself
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.yaml
Summary: 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 annotation argocd.argoproj.io/sync-options: Prune=false. PruneLast=true deletes only after the other resources are applied and healthy.
  • Flux: spec.prune: true on a Kustomization (the flux create kustomization default). Protect an object with the label or annotation kustomize.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?

  1. Turn off self-heal
  2. Remove replicas from the manifest when autoscaling is enabled, so only the HPA sets it
  3. Set the HPA's minReplicas to 2
  4. Run kubectl scale after each sync

Why doesn't imagePullPolicy: IfNotPresent, added by the API server, show up as drift?

  1. Argo CD and Flux compare only the fields the desired manifest sets (dry-run apply / three-way diff)
  2. Defaults are stored in Git automatically
  3. Pull policies are ignored by Kubernetes
  4. It does show up as drift

In Argo CD, what protects one critical object from automated pruning?

  1. A finalizer
  2. The annotation argocd.argoproj.io/sync-options: Prune=false
  3. Putting it in another namespace
  4. selfHeal: false