TExcelTAD
Home › GitOps: Argo CD & Flux › Sync Policies: Auto-Sync, Self-Heal & Prune

Sync Policies: Auto-Sync, Self-Heal & Prune

A sync is Argo CD applying the rendered desired state to the cluster. The syncPolicy of an Application decides when syncs happen on their own and how they apply objects.

Manual or automated

yaml
spec:
  syncPolicy:
    automated:            # present = automated sync; absent = manual (press Sync / argocd app sync)
      enabled: true       # lets you switch automation off without deleting the block
      prune: false        # delete objects removed from Git (default false)
      selfHeal: false     # re-sync when the cluster drifts, not only when Git changes (default false)
      allowEmpty: false   # allow syncing to "zero objects" (default false: protects against wiping the app)

The rules the controller follows for automated sync (from the Argo CD docs):

  1. It syncs only when the app is OutOfSync.
  2. It doesn't sync again to a commit (and parameters) it already synced successfully, unless selfHeal is on: that is what self-heal adds.
  3. It doesn't retry a failed sync against the same commit and parameters; the next new commit tries again (or configure retry, below).
  4. Rollback is impossible while automation is on: the next pass would sync back to Git (History & Rollback).

The decision, modelled

python · try it yourself
def should_auto_sync(app, policy):
    if not policy.get("automated") or policy["automated"].get("enabled") is False:
        return "no: manual sync policy"
    if app["sync"] == "Synced":
        return "no: already Synced"
    last = app.get("last_sync")                     # (revision, result)
    if last and last[0] == app["revision"]:
        if last[1] == "Failed":
            return "no: last sync of this revision failed (retry is off)"
        if not policy["automated"].get("selfHeal"):
            return "no: revision already synced; drift is left alone (selfHeal off)"
        return "yes: self-heal drift"
    return "yes: new revision " + app["revision"]

policy = {"automated": {"prune": True, "selfHeal": False}}
cases = [
    ("new commit",            {"sync": "OutOfSync", "revision": "b2", "last_sync": ("a1", "Succeeded")}),
    ("manual kubectl edit",   {"sync": "OutOfSync", "revision": "b2", "last_sync": ("b2", "Succeeded")}),
    ("broken manifest",       {"sync": "OutOfSync", "revision": "c3", "last_sync": ("c3", "Failed")}),
    ("nothing changed",       {"sync": "Synced",    "revision": "c3", "last_sync": ("c3", "Succeeded")}),
]
for name, app in cases:
    print(f"{name:21} {should_auto_sync(app, policy)}")
policy["automated"]["selfHeal"] = True
print(f"{'kubectl edit+selfHeal':21} {should_auto_sync(cases[1][1], policy)}")
new commit            yes: new revision b2
manual kubectl edit   no: revision already synced; drift is left alone (selfHeal off)
broken manifest       no: last sync of this revision failed (retry is off)
nothing changed       no: already Synced
kubectl edit+selfHeal yes: self-heal drift

Sync options

syncOptions change how objects are applied. They can be set on the Application (all objects) or on one object with the annotation argocd.argoproj.io/sync-options.

Option Effect Use when
CreateNamespace=true creates the destination namespace if missing the app owns its namespace
ServerSideApply=true uses Kubernetes server-side apply instead of client-side kubectl apply large objects (CRDs over the annotation size limit), shared field ownership
ApplyOutOfSyncOnly=true applies only objects that differ apps with thousands of objects
PruneLast=true prunes after everything else is applied and healthy safer replacements (new Service before the old one goes)
PrunePropagationPolicy=foreground how deletions cascade (foreground, background, orphan)
RespectIgnoreDifferences=true don't overwrite fields listed in ignoreDifferences HPAs, injected fields (Drift)
Replace=true kubectl replace/create instead of apply objects that can't be patched; destructive, use sparingly
FailOnSharedResource=true fail if another Application already manages an object catch two apps fighting over one object
Validate=false skip schema validation on apply almost never
Prune=false / Delete=false (per object) never prune / never delete with the app PVCs, namespaces, CRDs

Retries

A sync can fail for transient reasons: a webhook not ready yet, a CRD installed a moment ago. retry makes Argo CD try again with exponential backoff:

bash · try it yourself
cat > app.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}
  syncPolicy:
    automated: {enabled: true, prune: true, selfHeal: true}
    syncOptions: [CreateNamespace=true, ServerSideApply=true, PruneLast=true]
    retry:
      limit: 5
      backoff: {duration: 10s, factor: 2, maxDuration: 3m}
EOF
kubeconform -strict -summary app.yaml
# a repo policy check in CI: every production app must self-heal and prune
yq 'select(.metadata.name == "*-production") | .metadata.name + ": selfHeal=" + (.spec.syncPolicy.automated.selfHeal | tostring) + " prune=" + (.spec.syncPolicy.automated.prune | tostring)' app.yaml
Summary: 1 resource found in 1 file - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0
linkly-production: selfHeal=true prune=true

The retry delays here are 10 s, 20 s, 40 s, 80 s and 160 s (capped at 3 minutes).

Manual syncs and previews (sample session)

Even with automation, you'll sync by hand to test, or to apply only a part of an app:

bash
argocd app diff linkly-staging                    # what would change (exit code 1 if anything)
argocd app sync linkly-staging --dry-run          # run the sync without applying
argocd app sync linkly-staging --prune            # sync and prune, for apps without automated prune
argocd app sync linkly-staging --resource apps:Deployment:linkly   # only one object
argocd app wait linkly-staging --health --timeout 300

Sample argocd app diff output:

text
===== apps/Deployment linkly-staging/linkly ======
151c151
<         image: ghcr.io/acme/linkly:1.5.0-rc.1
---
>         image: ghcr.io/acme/linkly:1.5.0-rc.2

argocd app diff --exit-code style checks are useful in CI to show reviewers the live impact of a pull request, but they need API access to Argo CD; rendering the change locally (as every session in this course does) needs nothing.

Test yourself

Automated sync is on, selfHeal is off, and someone edits a Deployment by hand. What does Argo CD do?

  1. Reverts it immediately
  2. Marks the app OutOfSync but doesn't sync, because that revision was already synced
  3. Deletes the Deployment
  4. Commits the change to Git

A sync of commit c3 failed because a manifest is invalid. With no retry configured, when will Argo CD try again automatically?

  1. Every 3 minutes
  2. When a new commit (or parameter change) arrives
  3. Never, even after new commits
  4. After the self-heal timeout

Which sync option prevents a sync from overwriting spec.replicas that you listed in ignoreDifferences?

  1. ApplyOutOfSyncOnly=true
  2. RespectIgnoreDifferences=true
  3. Replace=true
  4. PruneLast=true