Argo CD Hour 2: Application deep dive — manifest sources and sync control
- Explain how repo-server determines the manifest type (Helm / Kustomize / plain YAML directory / plugin), and be able to write a Kustomize overlay, a Helm repository chart, and an OCI Helm chart an Application for each; master
valueFiles/values/valuesObject/parametersprecedence. - Use multi-source Application (
sources+ref+$values) to keep the chart (apps/myapp) separate from the environment values (values/myapp/*.yaml) and know its limits and signs of misuse. - Choose sync options by scenario: ServerSideApply, CreateNamespace, Replace, PruneLast, RespectIgnoreDifferences, ApplyOutOfSyncOnly and so on, and explain the real kubectl behavior and risks of each option.
- Use sync waves and resource hooks (PreSync database migration Job, PostSync smoke test, SyncFail alert) to orchestrate the release order and set correctly
hook-delete-policy. - Understand the built-in health assessment and the Application health aggregation rules, and can use Lua to write custom health checks for CRDs and test them locally.
- Use ignoreDifferences (jsonPointers / jqPathExpressions / managedFieldsManagers) and system-level customization to eliminate “permanent OutOfSync”, and know the v3 default changes (status field, Server-Side Diff).
- Explain the default annotation-based resource tracking and how it differs from label tracking, plus migration risks and
installationID.
Hour 1 time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (kind cluster lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up | Check the Argo CD and podinfo-dev from Hour 1; fill in apps/myapp,values/myapp directories | Repository structure check | Minimal starting script |
| 1 | 00–06 | Manifest sources | Type detection order, Directory (recurse/include/exclude), Kustomize options, Helm repositories and OCI, Helm values precedence | repo-server rendering pipeline | Deploy the same podinfo from three sources |
| 2 | 06–13 | Multi-source Application | sources,ref,$values, same-name resource overrides, CLI limits, misuse signals | values merge precedence calculator | myapp chart + dev/prod values separation |
| 3 | 13–21 | Sync options | SSA and Server-Side Diff (new in 3.6), CreateNamespace + managedNamespaceMetadata, Replace/Force, PruneLast, Prune/Delete=false|confirm, ApplyOutOfSyncOnly, RespectIgnoreDifferences | Sync options → actual kubectl action simulator | Enable SSA and PruneLast for podinfo-dev |
| 4 | 21–28 | Sync Waves and hooks | Ordering by phase → wave → kind → name, delay between waves, PreSync/Sync/PostSync/SyncFail/Skip/PreDelete/PostDelete, deletion policies, Helm hook mapping | Core animation: full execution order of one sync | db-migrate → apply → smoke-test; cause a failure to trigger SyncFail |
| 5 | 28–35 | Health checks | Built-in assessment, App health aggregation (worst wins), custom Lua, wildcards, ignore-healthcheck, health during deletion (3.6) | Health aggregation + Lua assessor | Write a Lua health check for a self-built CRD Widget |
| 6 | 35–42 | ignoreDifferences | jsonPointers, jqPathExpressions, managedFieldsManagers, system-level .all, status ignored by default, annotation-level ignore, knownTypeFields | Diff normalization simulator | HPA changing the replica count no longer causes drift |
| 7 | 42–50 | Resource tracking | annotation / annotation+label / label, tracking-id format, chart instanceLabelKey, installationID, v2 → v3 migration risks | “Who owns this resource?” resolver | Check the tracking-id and reproduce the false positive from “copied labels” |
| 8 | 50–60 | Capstone lab | Combine the first 7 modules in a myapp release: multi-source + SSA + hooks + waves + health + ignored differences | Fault-injection simulator + troubleshooting decision tree | End-to-end release and failure drill |
| — | After class | Cheat sheet · Capstone lab | Design a “production-grade Application” for podinfo-prod | Final quiz: 12 questions | Capstone lab |
Knowledge coverage matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / fields | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Write Applications for different manifest types | ✓ | ✓ | · | · | · | · | · | ✓ | spec.source.kustomize/helm/directory | Deploy podinfo from three sources |
| Helm values layers and precedence | ✓ | ✓ | · | · | · | · | · | ✓ | valueFiles,valuesObject,parameters | myapp dev/prod |
| Multi-source and values separation | · | ✓ | · | · | · | · | · | ✓ | sources,ref,$values | myapp-dev |
| Choose sync options | · | · | ✓ | · | · | ✓ | ✓ | ✓ | syncOptions,argocd app sync --server-side | podinfo-dev SSA |
| Orchestrate the release order | · | · | ✓ | ✓ | ✓ | · | · | ✓ | sync-wave,hook,hook-delete-policy | hooks-demo |
| Custom health checks | · | · | · | ✓ | ✓ | · | · | ✓ | resource.customizations.health.* | Widget CRD |
| Eliminate false-positive OutOfSync | ✓ | · | ✓ | · | · | ✓ | · | ✓ | ignoreDifferences,argocd app diff | HPA replica count |
| Resource ownership and tracking methods | · | · | · | · | · | · | ✓ | ✓ | argocd.argoproj.io/tracking-id | Copied-label lab |
| Sync failure troubleshooting | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | argocd app get --show-operation | Failure drill |
Topics excluded from this lesson (and where to learn them)
| Topic | Why it is not in this lesson | Where to learn |
|---|---|---|
| Writing Helm charts, template functions, Kustomize syntax itself | This lesson only covers how Argo CD invokes them | Helm 8 hours,Kubernetes 8 hours |
| App of Apps, ApplicationSet, progressive sync (RollingSync) | Belongs to “multi-application management” | Hour 3 |
| Private repository credentials, credential templates, SOPS / CMP plugins | Belongs to the security and secrets topic | Hour 5 |
| Argo Rollouts canary, sync windows | Belongs to progressive delivery | Hour 6 |
| Source Hydrator, controller sharding and performance tuning, deep diagnosis of OutOfSync loops | Requires the scaling background from Hour 7 | Hour 7 |
How to use these course materials
Principle · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Audio · Video. The “Animation” in Module 4 is the core of this lesson; play it through at least twice (once for success, once with an injected failure).
Progress counts once your quiz score is ≥ 70% or you click “Mark module complete”. It is saved in this browser (if local storage is blocked, it is cleared on refresh).
The “Audio” page reads the narration aloud with the browser’s built-in Web Speech API (en-US); without a Chinese voice pack, the script can still be read or passed to a TTS tool.
status field differences; v3.1 makes Server-Side Diff Stable and introduces native OCI sources (Beta at that time); v3.3 adds PreDelete hooks; from v3.5 repo-server has built-in Helm v4 (4.2.0),spec.source.helm.version are ignored; from v3.6 enabled ServerSideApply=true Applications automatically use Server-Side Diff. For older versions, follow the documentation for that version.Module 0 · Warm-up: gitops-lab repository structure
- CompletedHour 1: kind cluster
lab(contextkind-lab); usehelm upgrade --install argocd argo/argo-cd --version 10.18.0 -n argocd -f ~/gitops-lab/bootstrap/argocd-values.yamlinstalled Argo CD; GitHub repositoryhttps://github.com/<you>/gitops-lab(local~/gitops-lab, branchmain), which containsapps/podinfo/baseandoverlays/dev|staging|prod; Applicationpodinfo-dev(manifests inargocd/apps/podinfo-dev.yaml). - Tools: kubectl 1.37, kind v0.33.0, helm, git, argocd CLI v3.6.1. Already used
argocd login localhost:8080 --username admin --insecureto log in (lab passwordLab-Argo-2026!; the initial password Secret was deleted in Hour 1, so you need to firstkubectl -n argocd port-forward svc/argocd-server 8080:443, and it is recommended to keep it running in a separate terminal). - State at the end of Hour 1: dev overlay image
newTagis 6.17.0, while staging/prod are still 6.16.0;podinfo-devis managed declaratively (automated + prune + selfHeal,CreateNamespaceandPruneLast, retry 3 times,resources-finalizer), staging/prod have no Application yet. - It is recommended to first complete Helm 8 hours(especially building your own myapp chart and the Argo CD introduction in Helm lesson 5). This lesson does not repeat chart authoring or Argo CD basics.
Step 1: Check the cluster, Argo CD and podinfo-dev
kubectl config use-context kind-lab kubectl -n argocd get pods argocd version --short argocd app list argocd app get podinfo-dev
NAME READY STATUS RESTARTS AGE argocd-application-controller-0 1/1 Running 0 1d argocd-applicationset-controller-6c9b7d8f5-x2kqp 1/1 Running 0 1d argocd-notifications-controller-7f6d9c8b4-qz8lm 1/1 Running 0 1d argocd-redis-5d8c7b9f6-hk2wd 1/1 Running 0 1d argocd-repo-server-6b9f7c5d8-7xjvn 1/1 Running 0 1d argocd-server-74c9d6b8f7-p4n2r 1/1 Running 0 1d argocd: v3.6.1+... argocd-server: v3.6.1+... NAME CLUSTER NAMESPACE PROJECT STATUS HEALTH SYNCPOLICY ... argocd/podinfo-dev https://kubernetes.default.svc podinfo-dev default Synced Healthy Auto-Prune ...
Step 2 (only if you do not have the Hour 1 results): minimal starting point
If the cluster or Argo CD has been deleted, rebuild the minimal environment this lesson needs in about 5 minutes, in the order below. Repository contents (apps/podinfo/base and the three overlays) followHour 1, Module 0files in full, and push them. All labs in this lesson use the tags defined there app.kubernetes.io/name: podinfo, container name podinfod, and Service port 9898 as the reference.
# 1) Cluster (using the kind config saved in the repo in Hour 1)
kind create cluster --config ~/gitops-lab/bootstrap/kind-lab.yaml
kubectl config use-context kind-lab
# 2) Argo CD (the values file also comes from Hour 1; if you don't have it, omit -f and use the chart defaults)
helm repo add argo https://argoproj.github.io/argo-helm
helm repo update argo
helm upgrade --install argocd argo/argo-cd -n argocd --create-namespace \
--version 10.18.0 -f ~/gitops-lab/bootstrap/argocd-values.yaml --wait --timeout 10m
# 3) Log in (open another terminal and keep the port-forward running)
kubectl -n argocd port-forward svc/argocd-server 8080:443
argocd admin initial-password -n argocd # get the initial password on a fresh install
argocd login localhost:8080 --username admin --insecure
argocd account update-password # in Hour 1 changed to the lab password Lab-Argo-2026!
kubectl -n argocd delete secret argocd-initial-admin-secret
# 4) podinfo-dev Application (same as the final version of the Hour 1 capstone lab)
cat > ~/gitops-lab/argocd/apps/podinfo-dev.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: podinfo-dev
namespace: argocd
labels:
app.kubernetes.io/part-of: podinfo
env: dev
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: default
source:
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
path: apps/podinfo/overlays/dev
destination:
server: https://kubernetes.default.svc
namespace: podinfo-dev
syncPolicy:
automated:
enabled: true
prune: true
selfHeal: true
allowEmpty: false
syncOptions:
- CreateNamespace=true
- PruneLast=true
retry:
limit: 3
backoff:
duration: 10s
factor: 2
maxDuration: 2m
EOF
kubectl apply -n argocd -f ~/gitops-lab/argocd/apps/podinfo-dev.yaml
argocd app wait podinfo-dev --health --timeout 180
Step 3: Add the repository directories for this lesson
This lesson adds three types of directories: apps/myapp (the myapp chart from the Helm course; here use helm create to quickly generate an equivalent version and switch to the podinfo image),values/myapp/ (environment values; Module 2 uses multi-source references),apps/hooks-demo/ (hook and wave examples for Module 4).
cd ~/gitops-lab mkdir -p values/myapp apps/hooks-demo apps/widgets # If you kept the myapp chart from the Helm course, copy it over directly: cp -r ~/helm-lab/myapp apps/myapp helm create apps/myapp # Replace the default nginx image with podinfo and change the port to 9898 sed -i 's#repository: nginx#repository: ghcr.io/stefanprodan/podinfo#' apps/myapp/values.yaml sed -i 's#^ port: 80# port: 9898#' apps/myapp/values.yaml sed -i 's#^appVersion: .*#appVersion: "6.17.0"#' apps/myapp/Chart.yaml helm lint apps/myapp helm template myapp apps/myapp | grep -E 'image:|containerPort'
==> Linting apps/myapp
[INFO] Chart.yaml: icon is recommended
1 chart(s) linted, 0 chart(s) failed
image: "ghcr.io/stefanprodan/podinfo:6.17.0"
containerPort: 9898
helm create In the generated template, the container port is taken from .Values.service.port, and the probes access the port named http port’s /, and podinfo on port 9898’s / returns 200, so the probes need no changes. When the image tag is empty, use appVersion, so set appVersion to 6.17.0. On macOS, sed -i must be written as sed -i ''.git add -A git commit -m "hour2: add myapp chart, values/ and hooks-demo directories" git push
Step 4: Install metrics-server (required for the HPAs in Modules 6 and 8)
Modules 6 and 8 create HPAs. Without metrics-server the HPA cannot get CPU metrics, and its condition is FailedGetResourceMetric, so Argo CD’s built-in HPA health check may judge it unhealthy, which in turn affects PostSync hook execution. As with Kubernetes Hour 2the same, install v0.9.1 (the kind lab environment needs --kubelet-insecure-tls):
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml
kubectl -n kube-system patch deployment metrics-server --type=json \
-p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
kubectl -n kube-system rollout status deploy/metrics-server
kubectl top nodes # data appears after about 60 seconds
--kubelet-insecure-tls Only for use on lab clusters.Warm-up: answer from memory (30 seconds)
In Argo CD, which component is responsible for “turning Git into YAML”, and which one for “comparing YAML with the cluster”?
repo-server clones the repository and renders the manifests (helm template / kustomize build / reading the directory), with results cached in Redis. application-controller takes the rendered output, diffs it against the live state in the informer cache, derives the Sync and Health status, and performs the sync. Modules 1–2 of this lesson happen in repo-server; Modules 3–7 happen in the controller.
In the Helm course, helm upgrade --install pre-upgrade hooks run. When Argo CD syncs a Helm chart, does it run helm upgrade ?
No. Argo CD only uses helm template to render, and manages the lifecycle itself (helm list it cannot see the release). Helm hook annotations are mapped to Argo CD hooks, which foreshadows Module 4.
Module 1 · Manifest sources: plain YAML, Kustomize, Helm and OCI
- State the tool detection order: explicit configuration (
helm:/kustomize:/directory:/plugin:) takes precedence; otherwise, if there isChart.yaml→ Helm; if there iskustomization.yaml→ Kustomize; everything else → Directory. - Write one Application each for a plain YAML directory, a Kustomize overlay, a Helm repository chart and an OCI Helm chart, and know how to use
argocd app manifeststo view the rendered output. - Remember the Helm values precedence:
parameters > valuesObject > values > valueFiles > the chart’s own values.yaml.
helm template. Importance:★★★★★ (the first decision every Application needs to make)What: what the Application’s “source” is
spec.source (or the spec.sources[]) of a multi-source Application tells Argo CD: where to fetch from (repoURL + targetRevision),which part to take (for a Git repository, use path, for a Helm repository, use chart),which tool to render with (auto-detected, or explicit helm / kustomize / directory / plugin block). Rendering is done by argocd-repo-server , and the result is a set of plain Kubernetes manifests; the subsequent comparison and sync do not depend on the source type.
| Source type | Detection criteria | What repo-server actually does (equivalent command) | Common fields |
|---|---|---|---|
| Directory (plain YAML / JSON) | No Chart.yaml or kustomization.yaml, or explicitly directory: | read .yaml/.yml/.json; by default it only reads the current directory | directory.recurse,include,exclude,jsonnet |
| Kustomize | kustomization.yaml / .yml / Kustomization | First apply the Application fields kustomize edit (such as setting the image or prefix), then kustomize build <path> | kustomize.images,namePrefix,namespace,replicas,patches,components,commonLabels |
| Helm (chart in Git) | path under, there is Chart.yaml | if needed helm dependency build, then helm template . --name-template <release> --namespace <dest> --kube-version … --values … --set … | helm.valueFiles,values,valuesObject,parameters,releaseName |
| Helm (HTTP repository) | Use chart: field,repoURL as https | fetch <chart>-<version>.tgz then helm template | same as above; targetRevision is the chart version (a semver range can be used) |
| Helm (OCI repository) | chart: + without a scheme repoURL (e.g. ghcr.io/stefanprodan/charts), or set repository credentials enableOCI | pull the chart artifact from the OCI registry, then helm template | same as above |
| Native OCI source (v3.1+) | repoURL: oci://… | Pull a single-layer OCI artifact and unpack it, then detect by directory contents (it can be plain YAML, Kustomize or a Helm chart) | path (an OCI Helm chart is fixed to .),targetRevision (tag or digest) |
Why: why the source type matters
- Auditable: changes to Kustomize overlays and Helm values are both Git diffs, so reviewers can see “which parameter changed” rather than hundreds of lines of rendered output.
- Reproducible: for a Helm source,
targetRevisionmust pin the chart version; a Git source pins a branch or tag. Using*orHEADmeans “goes live automatically as soon as upstream releases”. - Clear boundaries: Argo CD only renders, it does not execute
helm install/upgrade, sohelm listcannot see the release, and Helm’slookupfunctions also cannot get cluster data (there is no cluster connection during rendering).
How: the four ways to write Helm values and their precedence
source:
repoURL: https://stefanprodan.github.io/podinfo
chart: podinfo
targetRevision: 6.17.0
helm:
releaseName: podinfo # defaults to the Application name
valueFiles: # precedence 4: files inside the chart (or multi-source $values); later entries override earlier ones
- values-lab.yaml
ignoreMissingValueFiles: true
values: | # precedence 3: string form
ui:
color: "#34577c"
valuesObject: # precedence 2: object form; when both are present, values is ignored
replicaCount: 2
parameters: # precedence 1 (highest): equivalent to --set
- name: ui.message
value: "hello from argo cd"
- name: podAnnotations.team
value: "platform"
forceString: true # equivalent to --set-string
parameters > valuesObject > values > valueFiles > the chart’s own values.yaml. In production, it is recommended to keep values files in Git (multi-source, Module 2),parameters and reserve parameters for the few values that need a temporary CLI override. Otherwise configuration lives in both Git and the Application, and when troubleshooting it is hard to tell “which one is actually in effect”.When: how to choose
| Scenario | Recommended source | Reason |
|---|---|---|
| In-house service where environments differ only in image tag, replica count and a few patches | Kustomize overlay (podinfo in this course) | The overlay is the environment difference, and the diff is intuitive |
| Third-party components (ingress-nginx, cert-manager, kube-prometheus-stack) | Upstream Helm chart (HTTP or OCI) + values in Git (multi-source) | No copying of the upstream chart; upgrades only change the version number |
| In-house chart shared by several services | Chart in Git (apps/myapp) or published to an OCI registry | Versioned chart, environment values separated |
| Final manifests generated by CI (already rendered) | Directory or native OCI source | Argo CD no longer renders; “what you see is what gets deployed” |
| Needs SOPS decryption, cdk8s, custom generators | Config Management Plugin (sidecar) | Covered in Hour 5 |
helm template, and hooks are mapped to Argo CD hooks (Module 4). ② “spec.destination.namespace forces a change to the namespace in the manifests” — it only adds a namespace to resources that do not specify a namespace , and Kustomize can use kustomize.namespace to set it uniformly. ③ “For a Helm OCI repository, repoURL must be written as oci://” — for Helm-type OCI repositories,do not write a scheme; only the native OCI source in v3.1+ takes one oci://. The two are different mechanisms. ④ “The Directory type recurses into subdirectories” — by default it does not; you need directory.recurse: true.Architecture diagram: repo-server rendering pipeline
Flow chart: Helm values merging (lowest to highest)
Interactive animation: how repo-server renders one source
Select a source, then press “Play” or “Next”. Each step highlights a stage inside repo-server, and the terminal below shows the equivalent commands and logs that repo-server actually runs. Note that rendering the same commit a second time hits the cache directly.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
argocd app create | Create a single-source Application with the CLI | --repo --path --revision (Git); --helm-chart --revision (Helm repository); --directory-recurse,--kustomize-image,--values,--helm-set,--sync-option,--upsert |
argocd app set | Modify source parameters (changes the Application object) | -p name=value (Helm parameter),--values,--kustomize-image,--nameprefix,--release-name |
argocd app manifests | View rendered output | --source git (desired state, default) or --source live; --revision Specify the version |
argocd app get --show-params | View the Helm/Kustomize parameters currently in effect | Used to confirm whether the CLI overrides are still in place |
argocd repo add | Register a repository (required for private repositories; can be omitted for public ones) | --type helm --name,--enable-oci,--type oci |
kubectl kustomize / helm template | Reproduce repo-server’s rendering locally | Run it locally before committing, to avoid pushing rendering errors to Argo CD |
1) Kustomize: override the image with the CLI (for demonstration; in production, change Git instead)
argocd app set podinfo-dev --kustomize-image ghcr.io/stefanprodan/podinfo:6.17.0 argocd app get podinfo-dev --show-params argocd app manifests podinfo-dev | grep image: # Undo the CLI override and return to the overlay definition in Git argocd app unset podinfo-dev --kustomize-image ghcr.io/stefanprodan/podinfo
IMAGE
ghcr.io/stefanprodan/podinfo:6.17.0
image: ghcr.io/stefanprodan/podinfo:6.17.0
How to verify:kubectl get application podinfo-dev -n argocd -o yaml appears in spec.source.kustomize.images. Common errors: Forgetting unset means that later changes to the image tag in Git “have no effect”, because the override in the Application takes precedence. Production use: Use only temporarily for emergency rollbacks; afterwards, commit the same change to Git and unset it.
2) Helm repository chart: create with one command
argocd app create podinfo-helm \ --repo https://stefanprodan.github.io/podinfo --helm-chart podinfo --revision 6.17.0 \ --dest-server https://kubernetes.default.svc --dest-namespace podinfo-helm \ --helm-set replicaCount=2 --helm-set ui.message="hello from helm" \ --sync-option CreateNamespace=true argocd app sync podinfo-helm argocd app get podinfo-helm --show-params
application 'podinfo-helm' created ... NAME VALUE replicaCount 2 ui.message hello from helm
Common errors:--revision written as v6.17.0 (the podinfo chart version has no v prefix) → chart "podinfo" version "v6.17.0" not found.
3) Compare repo-server rendering with local rendering
cd ~/gitops-lab kubectl kustomize apps/podinfo/overlays/dev > /tmp/local.yaml argocd app manifests podinfo-dev > /tmp/argocd.yaml diff <(grep -v '^---' /tmp/local.yaml) <(grep -v '^---' /tmp/argocd.yaml) && echo "rendering matches"
The two may use different Kustomize versions (the one built into kubectl vs the one bundled with repo-server). If differences appear, first check whether they come from version-specific behavior. argocd app manifests The resource order in the output may differ from the local one, so sort before comparing if necessary.
Lab: the same podinfo, three sources
podinfo-raw (plain YAML directory),podinfo-helm (Helm repository, declarative),podinfo-oci (OCI Helm), and compare the rendering and resources. Resource usage is about 4 podinfo Pods (each requests 10m CPU / 32Mi), with no cloud cost.apps/podinfo-raw/.
cd ~/gitops-lab
mkdir -p apps/podinfo-raw
kubectl kustomize apps/podinfo/base > apps/podinfo-raw/podinfo.yaml
cat > argocd/apps/podinfo-raw.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: podinfo-raw
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
path: apps/podinfo-raw
directory:
recurse: false
include: "*.yaml"
destination:
server: https://kubernetes.default.svc
namespace: podinfo-raw
syncPolicy:
syncOptions:
- CreateNamespace=true
EOF
git add -A && git commit -m "podinfo-raw: plain YAML source" && git push
kubectl apply -f argocd/apps/podinfo-raw.yaml
argocd app sync podinfo-raw && argocd app wait podinfo-raw --healthcat > ~/gitops-lab/argocd/apps/podinfo-helm.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: podinfo-helm
namespace: argocd
spec:
project: default
source:
repoURL: https://stefanprodan.github.io/podinfo
chart: podinfo
targetRevision: 6.17.0
helm:
releaseName: podinfo
valuesObject:
replicaCount: 2
ui:
color: "#34577c"
parameters:
- name: ui.message
value: "hello from helm"
destination:
server: https://kubernetes.default.svc
namespace: podinfo-helm
syncPolicy:
syncOptions:
- CreateNamespace=true
EOF
argocd app delete podinfo-helm --yes 2>/dev/null # delete the same-named app created with the CLI on the “Commands” page (if any)
kubectl apply -f ~/gitops-lab/argocd/apps/podinfo-helm.yaml
argocd app sync podinfo-helm && argocd app wait podinfo-helm --health
kubectl -n podinfo-helm get deploy podinfo -o jsonpath='{.spec.replicas}{"\n"}'
2
repoURL without oci://.
cat > ~/gitops-lab/argocd/apps/podinfo-oci.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: podinfo-oci
namespace: argocd
spec:
project: default
source:
repoURL: ghcr.io/stefanprodan/charts # Helm OCI: do not write oci://
chart: podinfo
targetRevision: 6.17.0
destination:
server: https://kubernetes.default.svc
namespace: podinfo-oci
syncPolicy:
syncOptions:
- CreateNamespace=true
EOF
kubectl apply -f ~/gitops-lab/argocd/apps/podinfo-oci.yaml
argocd app sync podinfo-oci && argocd app wait podinfo-oci --health
argocd app list -o wide | grep podinfo
Equivalent native OCI syntax for v3.1+: repoURL: oci://ghcr.io/stefanprodan/charts/podinfo,path: .,targetRevision: 6.17.0 (do not write chart). If the pull fails, first use helm pull oci://ghcr.io/stefanprodan/charts/podinfo --version 6.17.0 to confirm on this machine that the network and artifact are available.
argocd app manifests to compare the Deployment differences among the three (the Helm chart ships more labels, probes and HPA toggles).
for a in podinfo-raw podinfo-helm podinfo-oci; do echo "== $a"; argocd app manifests $a | grep -E '^kind:|image:' ; done
argocd app delete podinfo-raw podinfo-oci --yes kubectl delete ns podinfo-raw podinfo-oci --ignore-not-found cd ~/gitops-lab && git rm -r -q apps/podinfo-raw argocd/apps/podinfo-raw.yaml argocd/apps/podinfo-oci.yaml 2>/dev/null; git commit -qm "cleanup m1" && git push -q
Namespaces created by CreateNamespace are not owned by the application; deleting the application does not delete them, so they must be removed manually.
Case 1: incident caused by automatic upgrade of an upstream chart
Problem: The team set the ingress-nginx targetRevision to 4.*. After upstream released a new minor version, Argo CD automatically rendered the new chart; the changed default value altered the annotation behavior of all Ingresses. Approach: Pin all Helm sources to exact versions; use Renovate / Dependabot to open PRs that bump the version number, with the PR including argocd app diff --revision output. Limitation: semver ranges suit auto-trying in the dev environment; do not use them in prod.
Case 2: Helm chart uses lookup renders empty
Problem: the chart uses lookup to read an existing Secret in order to “keep the password generated the first time”; in Argo CD it can never be read during rendering, so the password changes on every refresh and the app stays OutOfSync forever. Approach: Have the password supplied by External Secrets or Sealed Secrets (Hour 5), with the chart referencing the existing Secret name; or provide it explicitly in values. Limitation: repo-server does not connect to the cluster during rendering,lookup so the lookup always returns empty.
Case 3: CI produces rendered manifests and pushes them to OCI
Problem: The security team requires that “what is deployed is exactly the manifest that was scanned”. Approach: Render in CI and run policy checks (kubeconform, conftest), using oras push to push it as a single-layer OCI artifact and sign it; Argo CD uses oci:// source to deploy by digest. Limitation: The native OCI source requires the artifact to have only one layer, with a media type of application/vnd.oci.image.layer.v1.tar+gzip or a Helm chart type (can be extended via repo-server environment variables).
Common errors and fixes
ComparisonError: rpc error: code = Unknown desc = `kustomize build <path>` failed exit status 1: Error: accumulating resources: ...
Cause: The overlay references the wrong base path, the remote base is unreachable, or it uses a field not supported by the Kustomize version in repo-server.
kubectl kustomize apps/podinfo/overlays/dev # reproduce locally argocd app get podinfo-dev --hard-refresh kubectl -n argocd logs deploy/argocd-repo-server | grep -i kustomize | tail
Fix: Correct the path and push; if the remote base needs repository credentials, register the repository in Argo CD; if you need --enable-helm build parameters such as those, set them in argocd-cm settings kustomize.buildOptions.
Unable to generate manifests: ... chart "podinfo" version "v6.17.0" not found in https://stefanprodan.github.io/podinfo repository
Cause: The chart version number is wrong (an extra v, or the version does not exist).
helm repo add podinfo https://stefanprodan.github.io/podinfo helm search repo podinfo/podinfo --versions | head -5
Fix: Use a version that actually exists in index.yaml, for example 6.17.0.
failed to fetch chart: ... unsupported protocol scheme "oci" / 401 Unauthorized (OCI Helm)
Cause: The Helm-type OCI repository’s repoURL has oci:// prefix; or the private registry has no credentials.
Fix: For the Helm type, remove the prefix (ghcr.io/org/charts); for a private registry, use argocd repo add ghcr.io/org/charts --type helm --enable-oci --username … --password …. From v3.5, Helm v4 is built in; for OCI registries served over plain HTTP, set the following on the repository --insecure-oci-force-http.
The Application shows Synced but there are no resources in the cluster / only some were deployed
Cause: The Directory type does not recurse by default, so manifests in subdirectories are ignored; or include the pattern does not match any files.
argocd app manifests APP | grep -c '^kind:'
kubectl get application APP -n argocd -o jsonpath='{.spec.source.directory}'
Fix: Set directory.recurse: true, and check the include/exclude globs (remember to quote them).
Unable to generate manifests: ... error converting YAML to JSON / template: ... nil pointer evaluating interface {}
Cause: A Helm template error, or values are missing keys the template expects (for example valueFiles a file in it does not exist and is silently ignored, leaving values missing).
helm template myapp apps/myapp -f values/myapp/dev.yaml --debug | head -40
Fix: Reproduce locally and fix it; do not casually turn on ignoreMissingValueFiles which would mask path errors.
1. Without logging into the UI, check all resource types and images rendered by podinfo-helm.
argocd app manifests podinfo-helm | grep -E '^kind:|image:'
2. Use the CLI to change podinfo-helm’s Helm parameter replicaCount temporarily to 3, then revert it.
argocd app set podinfo-helm -p replicaCount=3 argocd app get podinfo-helm --show-params argocd app unset podinfo-helm -p replicaCount
Note: when an Application is managed declaratively, CLI changes are overwritten by the next kubectl apply (or by the App of Apps sync).
The Application sets both helm.values (replicaCount: 3) and helm.valuesObject (replicaCount: 2), and also parameters (replicaCount=4). What is the final replica count? What if you delete parameters?
With parameters present it is 4 (highest precedence). After deleting it, it is 2: when valuesObject is present, values is ignored. Keep only one style, and move environment differences back into the values file in Git.
Verified teaching videos
Official docs
Video storyboard script (about 90 seconds)
These course materials cannot directly generate video or MP3; the storyboard and narration script are provided and can be handed to a video tool.
Visual: three source icons (Git folder, Helm repository, OCI registry) point to the same repo-server box.
Narration: Argo CD does not care how the manifests were written; it only requires repo-server to finally hand over a set of plain Kubernetes manifests.
Visual: repo-server’s internal decision tree: explicit config? Chart.yaml? kustomization.yaml? Otherwise directory.
Narration: first check whether the Application explicitly specifies a tool, then check whether the directory has Chart.yaml or kustomization.yaml; if neither exists, treat it as a plain YAML directory.
Visual: five transparent film layers stacked together: chart values, valueFiles, values, valuesObject, parameters, with the top layer most prominent.
Narration: the closer Helm values are to the Application, the higher their priority, and parameters is highest. In production, keep environment differences in the values file in Git.
Visual: the Redis cache icon lights up, and the second request returns directly.
Narration: the same commit is rendered only once and the result is cached in Redis, so only a hard refresh forces a re-render.
Module 2 · Multi-source Applications and Helm values separation
ref and $values to combine them into one application- Write a multi-source Application: one source provides the chart (
apps/myapp), another source only provides values (ref: values), and invalueFiles, use$values/values/myapp/dev.yamlto reference it. - Explain
$valuesthe resolution rules: it may only appear at the start of a path, and always points to the repository root directory; withrefsource cannot havechart. - Know the limits of multi-source: a same-name resource “later overrides earlier” and produces
RepeatedResourceWarning; the CLI can only use--fileto create; more than 2–3 sources is basically misuse.
What: the sources array
Specifying spec.sources (plural), Argo CD will ignore spec.source, render each source separately, and then merge the results into one application’s desired state. A source can have ref field, becoming a “file repository that other sources can reference”; if it does not set path, then only serves as a values file source and produces no resources itself.
spec:
sources:
- name: chart # optional source name; the CLI can locate it with --source-name
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
path: apps/myapp # chart source: produces resources
helm:
releaseName: myapp
valueFiles:
- values.yaml # relative to the chart directory (built into the chart)
- $values/values/myapp/dev.yaml # $values = repository root of the source below
- name: env-values
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
ref: values # defines the variable name $values; no path → only provides files
Why: why separate out the values
- Do not copy the upstream chart: when using
prometheus-community,ingress-nginxand other external charts, the chart comes from a Helm repository while your own values live in your own Git repository; upgrades only changetargetRevision. - Separation of responsibilities: the platform team maintains the chart (or chart repository), and application teams only maintain
values/myapp/*.yaml; the two repositories can have different review rules. - Independent versions: the chart source is pinned to a tag (such as
myapp-0.2.0), while the values source followsmain; it is immediately clear whether a change is to the chart or to configuration.
How: resolution rules and common pitfalls
| Rule | Description |
|---|---|
$<ref> Can only be written at the start of a path | $values/values/myapp/dev.yaml correct; values/$values/dev.yaml is not replaced. |
| Always relative to the repository root of the referenced source | even if the referencing source sets path,$values still points to the repository root. |
With ref source cannot have chart | does not support “using another Helm chart as the values source”. |
The referenced source sets path | it is also rendered as a normal source and produces resources (for example, also deploying a ConfigMap directory). |
| Same-name resources (same group/kind/namespace/name) | the last source that produces the resource takes effect, and a RepeatedResourceWarning condition appears; it can be used to “override a resource in the chart with the version in Git”. |
| Created with the CLI | --repo,--path and other single-source parameters do not apply; use argocd app create NAME --file app.yaml. To modify one source, use argocd app set --source-position N or --source-name. |
When: when to use / not use
| Suitable for | Not suitable (use instead) |
|---|---|
| External Helm chart + own values (the most typical case) | Bundling multiple unrelated apps together → use App of Apps or ApplicationSet (Hour 3) |
| Chart and environment configuration maintained by different teams and repositories | More than 2–3 sources → the official docs explicitly warn “almost certainly misuse” |
| chart + a small Git directory (extra NetworkPolicy, ConfigMap) | Only multi-environment differences → a Kustomize overlay or single-source Helm with multiple valueFiles is simpler |
$values ① “A path is relative to the referencing source’s path” — no, it is always relative to the repository root. ② “A values source without a path will still deploy YAML from the repository root” — no, without a path it only provides files. ③ “Writing both source and sources allows a smooth migration” — no: sources when source is present, source sources is completely ignored. ④ “Multi-source can replace ApplicationSet for managing multiple environments” — each environment should still be its own Application (myapp-dev, myapp-prod); otherwise an error in one environment leaves the whole application Degraded.Architecture diagram: the two sources of myapp-dev
Repository layout: chart and values separated
Interactive calculator: which values are finally in effect?
Check which layers are set image.tag and replicaCount (values on the right can be edited); click “Calculate”, and the animation merges layer by layer from lowest to highest, with the terminal below showing the equivalent repo-server helm template command.
| Layers (low → high) | Enabled | image.tag | replicaCount |
|---|---|---|---|
| apps/myapp/values.yaml (chart default) | |||
| valueFiles: $values/values/myapp/dev.yaml | |||
| helm.values (string) | |||
| helm.valuesObject | |||
| helm.parameters (--set) |
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
argocd app create NAME --file app.yaml | Create a multi-source application from a manifest | Single-source parameters (--repo,--path,--helm-set) and --file used together are ignored; --upsert Update an existing application |
argocd app get NAME | View each source’s revision and status | --source-position N / --source-name View one source; --show-params |
argocd app manifests NAME | View the merged manifests | --source-positions 1 --revisions <sha> Specify a source’s version |
argocd app set NAME --source-position 1 … | Modify the Nth source (counting from 1) | for example --source-position 1 --revision myapp-0.2.0 |
argocd app diff NAME --revisions … --source-positions … | Preview the diff after changing a source’s version | A multi-source application cannot use only --revision |
1) Render the template with envsubst, then create
export GH_USER=<you> envsubst < ~/gitops-lab/argocd/apps/myapp-dev.tmpl.yaml | argocd app create myapp-dev --file -
The official docs’ approach: the application name is taken from the manifest’s metadata.name. This course recommends applying directly kubectl apply -f for declarative management; the CLI approach is for one-off experiments.
2) Upgrade only the chart source to the new version and preview
argocd app diff myapp-dev --source-positions 1 --revisions myapp-0.2.0 argocd app set myapp-dev --source-position 1 --revision myapp-0.2.0
Common errors: Positions count from 1, so writing 0 produces an error; when managing declaratively, CLI changes are overwritten by the next apply, so for formal upgrades modify the Application manifest in Git.
3) Check whether duplicate resource warnings appear
kubectl -n argocd get application myapp-dev -o jsonpath='{range .status.conditions[*]}{.type}{": "}{.message}{"\n"}{end}'
RepeatedResourceWarning: Resource /ConfigMap/myapp-dev/myapp-extra appeared 2 times among application resources.
Lab: myapp chart + dev/prod values separation
myapp-dev and myapp-prod two multi-source Applications, with the chart for both coming from apps/myapp, with values from values/myapp/dev.yaml and prod.yaml. Resources: 4 podinfo Pods, no cloud cost.cd ~/gitops-lab
cat > values/myapp/dev.yaml <<'EOF'
replicaCount: 1
image:
tag: "6.16.0"
podAnnotations:
env: dev
resources:
requests:
cpu: 10m
memory: 32Mi
EOF
cat > values/myapp/prod.yaml <<'EOF'
replicaCount: 3
image:
tag: "6.17.0"
podAnnotations:
env: prod
resources:
requests:
cpu: 50m
memory: 64Mi
limits:
memory: 256Mi
EOF
# verify the merged result locally first
helm template myapp apps/myapp -f apps/myapp/values.yaml -f values/myapp/prod.yaml | grep -E 'replicas:|image:'
replicas: 3
image: "ghcr.io/stefanprodan/podinfo:6.17.0"for ENV in dev prod; do
cat > argocd/apps/myapp-$ENV.yaml <<EOF
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp-$ENV
namespace: argocd
spec:
project: default
sources:
- name: chart
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
path: apps/myapp
helm:
releaseName: myapp
valueFiles:
- values.yaml
- \$values/values/myapp/$ENV.yaml
- name: env-values
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
ref: values
destination:
server: https://kubernetes.default.svc
namespace: myapp-$ENV
syncPolicy:
syncOptions:
- CreateNamespace=true
EOF
done
grep -n 'values/myapp' argocd/apps/myapp-*.yaml
git add -A && git commit -m "myapp: multi-source dev/prod" && git push
kubectl apply -f argocd/apps/myapp-dev.yaml -f argocd/apps/myapp-prod.yaml
The heredoc end marker is not quoted, so $ENV will be substituted; \$values the backslash before it ensures the file gets the literal $values. Use grep to confirm the file contains - $values/values/myapp/dev.yaml.
argocd app sync myapp-dev myapp-prod argocd app wait myapp-dev myapp-prod --health --timeout 180 kubectl get deploy -A -l app.kubernetes.io/instance=myapp -o custom-columns=NS:.metadata.namespace,REPLICAS:.spec.replicas,IMAGE:.spec.template.spec.containers[0].image argocd app get myapp-prod -o json | jq '.status.sync.revisions'
NS REPLICAS IMAGE myapp-dev 1 ghcr.io/stefanprodan/podinfo:6.16.0 myapp-prod 3 ghcr.io/stefanprodan/podinfo:6.17.0 [ "3f9c2e1...", "3f9c2e1..." ]
app.kubernetes.io/instance=myapp is helm create the label generated by the template (its value is releaseName), unrelated to Argo CD’s resource tracking (Module 7).
values/myapp/dev.yaml ’s replicaCount to 2 and push, then argocd app diff myapp-dev --refresh, confirm that only one replicas line differs, then argocd app sync myapp-dev.argocd app delete myapp-dev myapp-prod --yes && kubectl delete ns myapp-dev myapp-prod.Case 1: kube-prometheus-stack values kept in the platform repository
Problem: The team used to copy the entire upstream chart into Git, so every upgrade required merging thousands of lines of diff. Approach: Multi-source: source 1 is https://prometheus-community.github.io/helm-charts chart with a pinned version; source 2 is the platform repository ref: values,valueFiles: [$values/platform/monitoring/common.yaml, $values/platform/monitoring/prod.yaml]. Limitation: Commits in each of the two repositories trigger refreshes separately; the webhook must be configured for both repositories (Hour 7).
Case 2: override one resource in the chart with a resource from Git
Problem: The upstream chart’s PodDisruptionBudget is hard-coded minAvailable: 1, which does not meet production requirements, and you do not want to fork the chart. Approach: Add a second Git source (with a path) that provides a same-name PDB, relying on the “later source overrides” rule; keep in the Application RepeatedResourceWarning and document it. Limitation: Relies on implementation details; the override breaks if the chart is renamed. Prefer sending a PR upstream or using a switch the chart provides.
Case 3: one application with 7 sources
Problem: A team put the frontend, backend, database and monitoring rules into 7 sources of one Application; if any source fails to render, the whole application cannot sync, and rollback can only be done as a whole. Approach: Split into 4 Applications, organized with App of Apps or ApplicationSet (Hour 3); cross-application ordering uses sync waves applied to the Application resources themselves (requires restoring the Application health check; see Module 5).
Common errors and fixes
Unable to generate manifests: ... open <path>/$values/values/myapp/dev.yaml: no such file or directory
Cause:$values Not substituted: the referenced source does not set ref: values, the name is misspelled ($value), or $values is not written at the start of the path.
kubectl -n argocd get application myapp-dev -o jsonpath='{range .spec.sources[*]}{.ref}{" "}{.path}{"\n"}{end}'
Fix: Ensure ref name matches $name is consistent, and written at the start of the path.
The path in valueFiles exists but cannot be read (the file is in a subdirectory of the values source’s path)
Cause: Mistakenly thought $values is relative to the referenced source’s path. In fact it is always relative to the repository root.
Fix: Write the full path $values/<path from the repository root>.
argocd app create myapp-dev --repo ... --path ... creates a single-source application / the parameters are ignored
Cause: Single-source parameters cannot describe multiple sources; together with --file used at the same time, they are ignored.
Fix: Write the full manifest,argocd app create myapp-dev --file app.yaml or kubectl apply -f.
RepeatedResourceWarning: Resource apps/Deployment/myapp-dev/myapp appeared 2 times among application resources.
Cause: Both sources produce the same resource (common when the values source is mistakenly set to path, so old manifests in Git are deployed too).
argocd app manifests myapp-dev | grep -A3 '^kind: Deployment'
Fix: If the override is not intentional, remove the values source’s path or delete the duplicate file.
Changed values/myapp/prod.yaml, but myapp-prod took a long time to become OutOfSync
Cause: Without a webhook, it relies on periodic refresh (timeout.reconciliation 120s + up to 60s jitter).
Fix: In the lab, run argocd app get myapp-prod --refresh; in production, configure the Git webhook (Hour 7).
1. Check the revision currently synced for myapp-prod’s second source (the values source).
argocd app get myapp-prod -o json | jq -r '.status.sync.revisions[1]' # or argocd app get myapp-prod --source-position 2
2. List the names of all multi-source applications with one command.
kubectl -n argocd get applications -o json | jq -r '.items[] | select(.spec.sources != null) | .metadata.name'
You want to deploy Redis using bitnami’s OCI chart (registry-1.docker.io/bitnamicharts), with values stored in gitops-lab/values/redis/prod.yaml. Write out the sources, and name two easy-to-make mistakes.
sources:
- repoURL: registry-1.docker.io/bitnamicharts # Helm OCI, do not write oci://
chart: redis
targetRevision: <exact version>
helm:
valueFiles:
- $values/values/redis/prod.yaml
- repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
ref: valuesPitfalls: ① the Helm OCI repoURL has had oci:// added; ② $values the path is assumed to be relative to some path; ③ a range version causes automatic upstream upgrades.
Verified teaching videos
Official docs
Video storyboard script (about 80 seconds)
These course materials cannot directly generate video/MP3; the storyboard and narration script are provided and can be handed to a video tool.
Visual: a thick upstream chart on the left, a thin values sheet on the right, with a line between them labeled ref colon values.
Narration: a multi-source application lets you avoid copying the upstream chart and maintain only your own values.
Visual: the path string $values/values/myapp/dev.yaml, with $values highlighted and replaced by a repository-root icon.
Narration: the dollar-sign values always points to the root directory of the referenced repository, and it can only be written at the start of the path.
Visual: both sources produce a same-name ConfigMap; the later one covers the earlier, with a yellow warning popping up beside it.
Narration: when two sources produce the same resource, the later source takes effect, and Argo CD issues a duplicate resource warning.
Visual: one application with seven sources, marked with a red cross; split into four independent applications, marked with a green check.
Narration: more than two or three sources usually means the application should be split into several applications, managed with ApplicationSet.
Module 3 · Sync options: ServerSideApply, CreateNamespace, Replace and PruneLast
- Distinguish application-level (
spec.syncPolicy.syncOptions) and resource-level (annotationargocd.argoproj.io/sync-options, comma-separated) sync options, and know that resource-level overrides application-level. - State the real action of each option: SSA =
kubectl apply --server-side --force-conflicts(field managerargocd-controller); Replace =kubectl replace/create; PruneLast = deletions are placed in the last implicit wave. - Know the new v3.6 behavior: applications with
ServerSideApply=trueenabled automatically use Server-Side Diff (can be reverted withServerSideDiff=falseannotation).
What: overview of sync options
| Option | Level | Actual effect | Typical use | Risk |
|---|---|---|---|---|
ServerSideApply=true | Application / resource | kubectl apply --server-side --force-conflicts; no longer writes last-applied-configuration annotation; from v3.6 the diff becomes Server-Side Diff | Large objects (CRDs exceeding the 262144-byte annotation limit), fields co-managed with other controllers, some patches | Forcibly takes over field ownership; Server-Side Diff adds API requests |
CreateNamespace=true | Application | Creates the target namespace if it does not exist; can be configured managedNamespaceMetadata to set labels and annotations | One namespace per application | Created namespaces are not tracked by default; deleting the application will not delete them |
Replace=true | Application / resource | Use kubectl replace (when it does not exist, create) instead of apply; takes precedence over SSA | Objects that cannot be applied (for example, fields that need full replacement) | May cause resources to be recreated or interrupted |
Force=true,Replace=true | resource | delete and recreate (delete/create) | Jobs that must re-run every time, changes to immutable fields | destructive; a standalone Force is ignored under SSA |
PruneLast=true | Application / resource | pruning is placed in the “last implicit wave”, after all waves succeed and resources are healthy | make new resources ready before deleting old ones (renaming a Service, migrating a ConfigMap) | old resources stay in the cluster if the sync fails |
Prune=false / Prune=confirm | Application / resource | never prune / require manual confirmation before pruning | critical resources such as PVCs and Namespaces | Prune=false keeps the application OutOfSync |
Delete=false / Delete=confirm | Application / resource | keep resources when the Application is deleted / require confirmation | keep PVCs and databases | leaves “orphans” that must be cleaned up manually |
ApplyOutOfSyncOnly=true | Application | apply only OutOfSync resources; hooks still run, and sync history is recorded as usual | large applications with thousands of resources; reduces API pressure and status size | edge cases when migrating from label to annotation tracking (Module 7) |
RespectIgnoreDifferences=true | Application | Before syncing, use ignoreDifferences to patch the desired state in advance; ignored fields are not overwritten back to the Git value | HPA manages replica count, webhook-injected fields (Module 6) | applies only to existing resources (fields are written as usual when creating) |
Validate=false | Application / resource | --validate=false | types using RawExtension, partial manifests with SSA | typos are no longer caught |
SkipDryRunOnMissingResource=true | Application / resource | skip dry-run when the CRD does not yet exist | CRDs created later by other controllers (such as Gatekeeper) | real typos are only exposed at sync time |
PrunePropagationPolicy=foreground|background|orphan | Application | cascade deletion policy when pruning (default foreground) | keep child resources (orphan) | orphan leaves ReplicaSets/Pods behind |
FailOnSharedResource=true | Application | fail the sync when a resource is found to be managed by another Application | prevents teams from overwriting each other | — |
ClientSideApplyMigration=false | Application | managedFields migration when disabling SSA (enabled by default) | rarely needed | — |
Why: what is wrong with the default client-side apply
By default, Argo CD performs the equivalent of kubectl apply client-side apply: a three-way merge (Git desired / live / kubectl.kubernetes.io/last-applied-configuration annotation). There are three problems: the annotation is limited to 262144 bytes, so large CRDs will report metadata.annotations: Too long; it cannot express “I only manage these fields”; and when an object is co-managed with other SSA-using controllers (HPA, Istio, cert-manager, etc.), ownership is unclear. Server-Side Apply has the API server track ownership per managedFields field, and Argo CD declares the fields it owns under the field manager argocd-controller name.
How: syntax
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: podinfo-dev
namespace: argocd
spec:
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions: # application-level: applies to all resources of this application
- CreateNamespace=true
- ServerSideApply=true
- PruneLast=true
managedNamespaceMetadata: # only takes effect when CreateNamespace=true
labels:
pod-security.kubernetes.io/enforce: baseline
team: platform
retry: # automatically retry failed syncs (exponential backoff)
limit: 3
backoff:
duration: 10s
factor: 2
maxDuration: 2m
---
# resource-level: set on the resource in Git; overrides application-level settings
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: data
annotations:
argocd.argoproj.io/sync-options: Prune=false,Delete=false
When: key decision points
- Enable SSA by default for new applications (common advice from the Argo CD community and Akuity), especially for objects that include large CRDs or are co-managed with controllers; from v3.6 it also automatically brings more accurate Server-Side Diff, and validating webhooks report errors already in the diff stage.
- CreateNamespace Suitable for labs and “one application per namespace”; in production, namespaces often need quotas, LimitRanges and labels, so a platform application should manage them separately (or use
managedNamespaceMetadata). - Replace / Force is a last resort; use it only through a resource-level annotation on the specific object that really needs it.
- PruneLast Used in refactors where “old and new resources need to coexist briefly”; it is not a data-protection tool, so protect data with
Prune=false/Delete=false.
Force=true alone can force a recreation” — it only takes effect together with Replace=true or during client-side apply; it is ignored under SSA. ② “ApplyOutOfSyncOnly is the same as selective sync (syncing only some resources)” — selective sync does not run hooks, while ApplyOutOfSyncOnly runs hooks as usual. ③ “Namespaces created by CreateNamespace are deleted when the application is deleted” — no, unless managedNamespaceMetadata a tracking annotation is set so the application “owns” it (the official docs warn you proceed at your own risk). ④ “With SSA enabled, HPA and Argo CD will not fight over replicas” — if replicas is written in Git, Argo CD still owns that field and will revert it; remove the field from the manifest, or use ignoreDifferences + RespectIgnoreDifferences (Module 6).Comparison diagram: client-side apply vs server-side apply
Timeline: PruneLast makes deletion happen last
Simulator: what happens in the same sync when different options are enabled
Scenario: podinfo-dev’s target namespace does not exist yet; a ConfigMap was deleted in Git legacy-config; the Deployment image changed; the Service is unchanged; and there is a 300KB CRD. Check the options, click “Sync”, and see the equivalent kubectl actions the controller actually performs and the result.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
argocd app set APP --sync-option X=Y | Add sync options to an application | repeatable; when managing declaratively, change the manifest in Git |
argocd app sync APP | Manual sync; behavior can be specified temporarily | --server-side,--replace,--force,--prune,--apply-out-of-sync-only,--dry-run,--preview-changes,--resource GROUP:KIND:NAME |
kubectl get … --show-managed-fields | View field owners | Confirm argocd-controller ’s operation: Apply |
argocd app diff APP --server-side-diff | Compute the diff using Server-Side Diff | Enabled by default when SSA or the annotation is enabled |
1) Enable SSA for podinfo-dev and confirm the field manager
argocd app set podinfo-dev --sync-option ServerSideApply=true argocd app sync podinfo-dev kubectl -n podinfo-dev get deploy podinfo --show-managed-fields -o json \ | jq -r '.metadata.managedFields[] | "\(.manager)\t\(.operation)"'
argocd-controller Apply kube-controller-manager Update argocd-controller Update
How to verify: appears argocd-controller Apply; the entries left behind by the earlier client-side apply Update entries will be gradually transferred through “client-to-server migration” (ClientSideApplyMigration enabled by default). Common errors: and Replace=true when set together, Replace takes precedence and SSA has no effect.
2) Sync only one resource (selective sync, hooks do not run)
argocd app sync podinfo-dev --resource apps:Deployment:podinfo argocd app sync podinfo-dev --resource :Service:podinfo # core group is empty
3) Preview before syncing
argocd app sync podinfo-dev --dry-run argocd app sync podinfo-dev --preview-changes
--preview-changes shows the diff first and asks for confirmation (interactive). In CI, it is common to use argocd app diff --exit-code to check whether anything changed.
Lab: enable SSA, namespace metadata and PruneLast for podinfo-dev
argocd/apps/podinfo-dev.yaml, building on the Hour 1 version (which already contains CreateNamespace,PruneLast) and add ServerSideApply and managedNamespaceMetadata, then demonstrate PruneLast and Prune=false. No cloud cost.cd ~/gitops-lab
cat > argocd/apps/podinfo-dev.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: podinfo-dev
namespace: argocd
labels:
app.kubernetes.io/part-of: podinfo
env: dev
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: default
source:
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
path: apps/podinfo/overlays/dev
destination:
server: https://kubernetes.default.svc
namespace: podinfo-dev
syncPolicy:
automated:
enabled: true
prune: true
selfHeal: true
allowEmpty: false
managedNamespaceMetadata: # new
labels:
pod-security.kubernetes.io/enforce: baseline
team: platform
syncOptions:
- CreateNamespace=true
- PruneLast=true # already present from Hour 1
- ServerSideApply=true # new
retry:
limit: 3
backoff:
duration: 10s
factor: 2
maxDuration: 2m
EOF
git add -A && git commit -m "podinfo-dev: SSA + namespace metadata" && git push
kubectl apply -n argocd -f argocd/apps/podinfo-dev.yaml
argocd app sync podinfo-dev
kubectl get ns podinfo-dev --show-labels
NAME STATUS AGE LABELS podinfo-dev Active 1d kubernetes.io/metadata.name=podinfo-dev,pod-security.kubernetes.io/enforce=baseline,team=platform
The namespace already exists and has no other labels, which meets the prerequisite in the official docs. If the namespace’s labels were previously changed with kubectl client-side, first migrate it to SSA management, otherwise existing labels may be lost.
demo-v1, sync, then rename it to demo-v2, and in the operation result, observe that the deletion of demo-v1 comes last.
cd ~/gitops-lab/apps/podinfo/overlays/dev cat > demo-cm.yaml <<'EOF' apiVersion: v1 kind: ConfigMap metadata: name: demo-v1 data: greeting: hello EOF kubectl kustomize . >/dev/null && sed -i 's#^- ../../base#- ../../base\n- demo-cm.yaml#' kustomization.yaml kubectl kustomize . | grep -A2 'kind: ConfigMap' git add -A && git commit -m "dev: add demo-v1" && git push && argocd app sync podinfo-dev sed -i 's/demo-v1/demo-v2/' demo-cm.yaml git commit -am "dev: rename demo-v1 -> demo-v2" && git push argocd app sync podinfo-dev argocd app get podinfo-dev --show-operation | sed -n '/GROUP/,$p'
GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE
ConfigMap podinfo-dev demo-v2 Synced configmap/demo-v2 serverside-applied
Service podinfo-dev podinfo Synced Healthy service/podinfo serverside-applied
apps Deployment podinfo-dev podinfo Synced Healthy deployment.apps/podinfo serverside-applied
ConfigMap podinfo-dev demo-v1 Pruned pruned
sed inserts - demo-cm.yaml into the resources list (GNU sed syntax); you can also edit it by hand.
demo-v2 an annotation to argocd.argoproj.io/sync-options: Prune=false and push; then remove demo-cm.yaml from kustomization and push again. The application will show OutOfSync,demo-v2 the resource still remains in the cluster, and the UI shows that pruning was skipped.
kubectl -n podinfo-dev get cm demo-v2 argocd app get podinfo-dev -o json | jq -r '.status.sync.status, (.status.resources[] | select(.name=="demo-v2") | "\(.kind)/\(.name) \(.status) requiresPruning=\(.requiresPruning)")'
NAME DATA AGE demo-v2 1 3m OutOfSync ConfigMap/demo-v2 OutOfSync requiresPruning=true
In the sync result the resource shows pruning as skipped (ignored / PruneSkipped); exact wording depends on your version.
kubectl -n podinfo-dev delete cm demo-v2, then confirm argocd app get podinfo-dev that it returns to Synced. The SSA and PruneLast settings are kept, and later modules continue to use them.Case 1: kube-prometheus-stack CRD exceeds the annotation limit
Problem: Sync reports The CustomResourceDefinition "prometheuses.monitoring.coreos.com" is invalid: metadata.annotations: Too long: must have at most 262144 bytes. Approach: application-level ServerSideApply=true (or add a resource-level annotation only to the CRDs). Limitation: From v3.6 this application automatically uses Server-Side Diff, and API server requests increase (results are cached).
Case 2: the namespace’s Pod Security labels are overwritten
Problem: The platform team labeled the namespace pod-security.kubernetes.io/enforce=restricted, and an application also enabled CreateNamespace and managedNamespaceMetadata wrote only team labels, so the security labels were lost after sync. Approach: Namespaces are managed uniformly by a platform application (the Namespace manifest in Git); business applications no longer use managedNamespaceMetadata; or the security labels are written in as well. Limitation: When a Namespace manifest with the same name exists in Git, it takes precedence over managedNamespaceMetadata.
Case 3: deleting an application accidentally deleted the database PVC
Problem: During a refactor the Application was deleted and recreated; the PVC was cascade-deleted and data was lost. Approach: Add uniformly to stateful resources argocd.argoproj.io/sync-options: Prune=false,Delete=false; when you need to migrate the application, first argocd app delete --cascade=false (delete only the Application, not the resources). Limitation: Retained resources must be re-“claimed” in the new application (same-name resources are automatically brought under tracking by the new application).
Common errors and fixes
namespaces "podinfo-dev" not found
Cause: The target namespace does not exist and there is no CreateNamespace=true, and there is no Namespace manifest in Git either.
Fix: Add CreateNamespace=true, or have a platform application create the namespace first (a sync wave can put the Namespace in an earlier wave).
metadata.annotations: Too long: must have at most 262144 bytes
Cause: client-side apply writes the entire object into last-applied-configuration annotation.
Fix:ServerSideApply=true (recommended) or Replace=true (only for that resource).
Apply failed with 1 conflict: conflict with "kubectl-client-side-apply" using apps/v1: .spec.replicas
Cause: Manually running SSA conflicts with other field managers. Argo CD itself uses --force-conflicts, so you usually will not see it; locally, with kubectl apply --server-side debugging, it appears.
kubectl get deploy podinfo -n podinfo-dev --show-managed-fields -o yaml | grep -B2 -A8 'manager:'
Fix: Confirm who should manage the field; if Argo CD should manage it, let Argo CD sync (take ownership); if not, remove the field from the Git manifest.
Deployment.apps "podinfo" is invalid: spec.selector: Invalid value: ... field is immutable
Cause: An immutable field was changed (selector, a Job’s template, etc.), so the apply cannot complete.
Fix: Add only to that resource argocd.argoproj.io/sync-options: Force=true,Replace=true to delete and recreate once (causes an outage); remove the annotation afterwards; or create a new resource under a different name together with PruneLast.
Sync stays in Running, with the message waiting for deletion of ... / Pods do not disappear for a long time after the resource is deleted
Cause: Default foreground cascade deletion needs to wait for child resources (Pods) to terminate; a finalizer has not completed.
kubectl get <kind> <name> -n <ns> -o jsonpath='{.metadata.finalizers}'
Fix: Investigate the blocking finalizer (covered in detail in Hour 7); if you really need fast deletion, you can use PrunePropagationPolicy=background.
1. Run a one-time Replace sync only for the Service in podinfo-dev (do not change Git).
argocd app sync podinfo-dev --resource :Service:podinfo --replace
2. List all applications that have ServerSideApply enabled.
kubectl -n argocd get applications -o json | jq -r '.items[] | select(.spec.syncPolicy.syncOptions[]? == "ServerSideApply=true") | .metadata.name'
You want to rename the Service api to api-v2, and the Ingress must switch to point to api-v2, with traffic uninterrupted throughout. How should this be configured?
In the same commit: add api-v2 and modify the Ingress; set on the application (or on the old Service) PruneLast=true, so the old Service is only deleted after all resources are healthy. If needed, use a sync wave so api-v2 comes before the Ingress (wave -1). Do not use Replace, and do not delete first and then create.
Verified teaching videos
Official docs
Video storyboard script (about 90 seconds)
These course materials cannot directly generate video/MP3; the storyboard and narration script are provided and can be handed to a video tool.
Visual: a very long last-applied annotation strip is cut with scissors; red text 262144.
Narration: the default client-side apply stuffs the whole object into an annotation, so large CRDs exceed the limit.
Visual: the field table in the API server, with an owner label next to each field: argocd-controller, kube-controller-manager.
Narration: server-side apply has the API server record who manages each field; Argo CD declares its fields under the name argocd-controller.
Visual: on the timeline, the deletion of the old Service is dragged to the end.
Narration: PruneLast puts deletion in the last wave; old resources are deleted only after the new resources are healthy.
Visual: the PVC icon is covered by a shield reading Prune=false, Delete=false.
Narration: protect data with resource-level annotations; do not rely on PruneLast.
Module 4 · Sync Waves and resource hooks: PreSync, PostSync, SyncFail
- State the ordering rules for sync tasks: phase → wave (lower first) → kind (foundational resources such as Namespaces first, CRs later) → name; after each wave is applied, wait for its resources to become healthy; by default there is a 2-second delay between waves (
ARGOCD_SYNC_WAVE_DELAY). - Can write a PreSync database migration Job, a PostSync smoke test, and a SyncFail notification, and select the correct
hook-delete-policy(defaults toBeforeHookCreation). - Know the boundaries of hooks: selective sync does not run hooks; PreSync hooks run before the Secrets/ConfigMaps of the same application’s Sync phase; they run on every sync; Helm hooks are mapped, but once any Argo CD hook is defined, all Helm hooks are ignored.
What: phases and hook types
| Hook / phase | When it runs | On failure | Typical use |
|---|---|---|---|
PreSync | Before applying any manifests | the whole sync stops and is marked failed (SyncFail hooks then run) | database migrations, pre-checks, backups |
Sync | after all PreSync hooks succeed, runs alongside applying regular manifests | Sync failed | tasks that must run in the same batch as the resources |
Skip | do not apply the manifest | — | skip unneeded resources in the chart (such as certain admission Jobs) |
PostSync | all Sync hooks complete, apply succeeds, and all resources are Healthy afterwards | sync marked failed | smoke tests, notifications, cache warm-up |
SyncFail | When the sync operation fails | only marks failure; no other actions | alerting, cleanup, rollback assistance |
PreDelete (v3.3+) | When an entire Application is deleted, before its resources are deleted (regular syncs and pruning do not trigger it) | deletion is blocked and the Application shows DeletionError | deregister services, export data |
PostDelete (v2.10+) | after all of the Application’s resources are deleted | the Application CR is kept and shows DeletionError | clean up external resources (DNS, cloud storage) |
Hooks are declared through annotations argocd.argoproj.io/hook (multiple can be comma-separated); they can be any resource type, most commonly Job, Pod or Argo Workflow. The PreSync and PostSync phases may contain only hooks; ordinary resources all belong to the Sync phase.
Why: why ordering is needed
- The database schema must be migrated before the new application version can start; the smoke test must run after the new version is ready.
- CRDs must come before CRs, and namespaces and ServiceAccounts must come before workloads (kind ordering already handles most of this; cross-application dependencies need waves).
- Without ordering, all resources are applied at once: migration and new Pods run concurrently, which may open a window where new code accesses the old schema.
How: execution algorithm (as described in the official docs)
- Sort all resources and hooks by: phase → wave (annotation
argocd.argoproj.io/sync-wave, integer, default 0, may be negative) → kind → name. - Find the first wave that has “OutOfSync or unhealthy resources”, and apply the resources in that wave.
- Wait for that wave’s resources to become healthy (hooks wait for completion: Job succeeded, Pod exited successfully), then wait
ARGOCD_SYNC_WAVE_DELAY(default 2 seconds, giving other controllers time to react and avoiding health judgments on old objects). - Repeat until all phases and waves are synced and healthy. When pruning, waves are processed in reverse order: higher waves are deleted first; if deletion fails in one wave, lower waves are no longer processed.
PruneLastdeletions (with PruneLast) are placed in the last implicit wave of the Sync phase.
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate # fixed name, used together with BeforeHookCreation
annotations:
argocd.argoproj.io/hook: PreSync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
argocd.argoproj.io/sync-wave: "-1" # ordering also works within the PreSync phase
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: busybox:1.37
command: ["sh", "-c", "echo migrating schema to v2; sleep 5"]
Hook deletion policies
| Policy | Behavior | Suited for |
|---|---|---|
HookSucceeded | Delete after the hook succeeds (Jobs/Workflows typically after completion) | smoke tests, notifications: successful ones need not be kept; failed ones are left for troubleshooting |
HookFailed | Delete after the hook fails | rarely used alone |
BeforeHookCreation (default) | Delete the old same-name hook before creating a new one; should be used with a fixed metadata.name | migration Job: keeps the most recent log until the next sync |
hook-delete-policy to clean up hooks,do not set on hook Jobs ttlSecondsAfterFinished: Argo CD needs to read the Job to judge the phase result; if Kubernetes deletes the Job early, the sync waits forever for a hook that no longer exists. When using generateName hooks, pair it with HookSucceeded, otherwise every sync leaves one behind.When: mapping to Helm hooks
| Helm annotation | Argo CD equivalent |
|---|---|
pre-install,pre-upgrade | PreSync (Argo CD does not distinguish install from upgrade; both run) |
post-install,post-upgrade | PostSync |
pre-delete / post-delete | PreDelete / PostDelete |
helm.sh/hook-weight | argocd.argoproj.io/sync-wave |
helm.sh/hook-delete-policy | supported, but evaluated using Argo CD’s phase semantics |
helm.sh/resource-policy: keep | sync-options: Delete=false |
pre/post-rollback,test-success/failure | not supported (ignored) |
Flow chart: phases and waves of one sync
State diagram: hook lifecycle and deletion policies
Core animation: full execution order of one sync
Application hooks-demo contains: PreSync Job db-migrate; Sync-phase ConfigMap (wave -1), Service and Deployment (wave 0), PDB (wave 1); the cluster also has an old ConfigMap that has been deleted from Git legacy-config (wave 0); PostSync Job smoke-test; SyncFail Job notify-failure. You can inject failures, toggle PruneLast, and then step through to observe the controller’s actual behavior and status messages.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
argocd app get APP --show-operation | View the phase, message and result of each task for the current or last sync operation | The HOOK column shows the hook type |
argocd app wait APP --operation | Wait for the sync operation to finish | --health,--timeout |
argocd app terminate-op APP | Terminate a running sync (e.g., stuck on a hook) | does not stop work the hook has already started |
argocd app logs APP --kind Job --name db-migrate | View hook logs (you can also use kubectl logs) | --group batch,--follow; from v3 it requires RBAC logs permission |
kubectl get jobs -n hooks-demo -w | Watch hook Job creation and deletion in real time | together with -o wide |
argocd app sync hooks-demo --async kubectl -n hooks-demo get jobs,deploy,cm,pdb -w argocd app get hooks-demo --show-operation
Operation: Sync
Sync Revision: 7c1e2a9...
Phase: Running
Message: waiting for completion of hook batch/Job/db-migrate
...
Phase: Succeeded
Message: successfully synced (all tasks run)
GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE
batch Job hooks-demo db-migrate Succeeded PreSync Reached expected number of succeeded pods
ConfigMap hooks-demo web-config Synced configmap/web-config serverside-applied
Service hooks-demo web Synced Healthy service/web serverside-applied
apps Deployment hooks-demo web Synced Healthy deployment.apps/web serverside-applied
policy PodDisruptionBudget hooks-demo web Synced Healthy poddisruptionbudget.policy/web serverside-applied
batch Job hooks-demo smoke-test Succeeded PostSync Reached expected number of succeeded pods
How to verify the order: In the -w output,db-migrate appears only after completion web-config, the PDB appears only after the Deployment is ready, and finally smoke-test. Common errors: Using --resource with selective sync, hooks do not run, which is mistakenly taken to mean “the hooks are broken”. Production use: Run in CI argocd app sync APP && argocd app wait APP --health --timeout 600, using the exit code to determine whether the release succeeded.
Lab: db-migrate → apply → smoke-test, with a deliberate failure
apps/hooks-demo/ write 6 manifests and create a manually synced application hooks-demo, observe the execution order; then make the smoke test fail and observe the SyncFail hook. Images: busybox:1.37,curlimages/curl:8.23.0, podinfo 6.17.0.cd ~/gitops-lab/apps/hooks-demo
cat > 00-config.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
name: web-config
annotations:
argocd.argoproj.io/sync-wave: "-1"
data:
PODINFO_UI_MESSAGE: "hooks-demo v2"
EOF
cat > 10-db-migrate.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate
annotations:
argocd.argoproj.io/hook: PreSync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: busybox:1.37
env:
- name: TARGET_SCHEMA # does not depend on a ConfigMap in the same application (it may not exist yet during PreSync)
value: "2"
command: ["sh", "-c", "echo \"migrating schema to v$TARGET_SCHEMA\"; sleep 8; echo done"]
EOF
cat > 20-web.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 2
selector:
matchLabels: {app: web}
template:
metadata:
labels: {app: web}
spec:
containers:
- name: podinfod
image: ghcr.io/stefanprodan/podinfo:6.17.0
envFrom:
- configMapRef: {name: web-config}
ports:
- {name: http, containerPort: 9898}
readinessProbe:
httpGet: {path: /readyz, port: http}
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector: {app: web}
ports:
- {name: http, port: 9898, targetPort: http}
EOF
cat > 25-pdb.yaml <<'EOF'
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: web
annotations:
argocd.argoproj.io/sync-wave: "1"
spec:
minAvailable: 1
selector:
matchLabels: {app: web}
EOF
cat > 30-smoke-test.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
generateName: smoke-test-
annotations:
argocd.argoproj.io/hook: PostSync
argocd.argoproj.io/hook-delete-policy: HookSucceeded
spec:
backoffLimit: 1
template:
spec:
restartPolicy: Never
containers:
- name: smoke
image: curlimages/curl:8.23.0
command: ["sh", "-c", "curl -fsS http://web:9898/healthz && curl -fsS http://web:9898/ | grep -q 'hooks-demo v2'"]
EOF
cat > 40-notify-failure.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
generateName: notify-failure-
annotations:
argocd.argoproj.io/hook: SyncFail
argocd.argoproj.io/hook-delete-policy: HookSucceeded
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
containers:
- name: notify
image: busybox:1.37
command: ["sh", "-c", "echo 'ALERT: hooks-demo sync failed, see argocd app get hooks-demo --show-operation'"]
EOF
ls
podinfo’s / returns JSON, in which message field comes from PODINFO_UI_MESSAGE, so the smoke test can verify the configuration is actually in effect. generateName hooks paired with HookSucceeded, to avoid Jobs accumulating with each sync.
cat > ~/gitops-lab/argocd/apps/hooks-demo.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: hooks-demo
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
path: apps/hooks-demo
destination:
server: https://kubernetes.default.svc
namespace: hooks-demo
syncPolicy:
syncOptions:
- CreateNamespace=true
- ServerSideApply=true
EOF
cd ~/gitops-lab && git add -A && git commit -m "hooks-demo: presync/postsync/syncfail + waves" && git push
kubectl apply -f argocd/apps/hooks-demo.yaml
# Terminal A: watch
kubectl create ns hooks-demo 2>/dev/null; kubectl -n hooks-demo get jobs,deploy,cm,pdb -w
# Terminal B: sync
argocd app sync hooks-demo
argocd app get hooks-demo --show-operation
On the first sync the namespace does not exist, and the PreSync Job also needs the namespace: CreateNamespace creates it before all tasks. Creating the namespace in terminal A in advance is only so that -w can start observing immediately.
kubectl -n hooks-demo logs job/db-migrate kubectl -n hooks-demo get jobs
migrating schema to v2 done NAME STATUS COMPLETIONS DURATION AGE db-migrate Complete 1/1 11s 2m
After smoke-test succeeds it is deleted by HookSucceeded, so it does not appear in the list.
hooks-demo v3, and add an annotation to the Pod template config-rev: "3" to trigger a rollout (a change to a ConfigMap read via envFrom does not restart Pods by itself); the smoke test still checks for v2, so it will fail:
cd ~/gitops-lab
sed -i 's/hooks-demo v2"/hooks-demo v3"/' apps/hooks-demo/00-config.yaml
sed -i 's/^ labels: {app: web}/ labels: {app: web}\n annotations: {config-rev: "3"}/' apps/hooks-demo/20-web.yaml
grep -n -A1 'labels: {app: web}' apps/hooks-demo/20-web.yaml
git commit -am "hooks-demo: message v3 (smoke test still expects v2)" && git push
argocd app sync hooks-demo; echo "exit=$?"
argocd app get hooks-demo --show-operation | head -12
kubectl -n hooks-demo get jobs
kubectl -n hooks-demo logs -l job-name --tail=3 --prefix
Phase: Failed Message: one or more synchronization tasks completed unsuccessfully ... exit=20 NAME STATUS COMPLETIONS AGE db-migrate Complete 1/1 40s notify-failure-x7k2p Complete 1/1 5s ← deleted by HookSucceeded after success, so it may not be visible smoke-test-b9q4d Failed 0/1 30s ← failed hooks are kept for troubleshooting
Sequence review: PreSync migration succeeds → wave -1 updates the ConfigMap → wave 0 rolls the Deployment and waits for health → wave 1 → PostSync smoke test fails → SyncFail alert. Exact failure messages and the CLI exit code (non-zero) depend on your environment. If you did not add config-rev the annotation, the Pods will not restart and the page still shows v2, so the smoke test passes instead. This is the classic trap of “the config changed but has no effect”.
30-smoke-test.yaml in the expected value to hooks-demo v3, and after pushing and syncing again it should succeed (the smoke-test Job left by the failure has a name generated by generateName, so it does not conflict and can be deleted manually). End of lab: argocd app delete hooks-demo --yes && kubectl delete ns hooks-demo (Module 8 recombines these mechanisms in myapp).Case 1: Flyway migration as a PreSync hook
Problem: The new service version depends on new columns. In the old process, migration ran at application startup, and concurrent migration across replicas caused lock waits. Approach: Split the migration into a PreSync Job (backoffLimit: 0 with a fixed name + BeforeHookCreation). Database credentials come from a Secret that already exists in the cluster (provided by ESO in another application). The migration tool records its own version, so running it again on every sync is idempotent. Limitation: The whole sync operation stays Running while the migration runs. Long migrations may time out, and terminating the operation does not stop a migration that has already started, so hand long tasks to Argo Workflows or a database operations process.
Case 2: ingress-nginx admission Job stalls the sync
Problem: When upgrading ingress-nginx (Helm chart), the sync stalls at waiting for completion of hook batch/Job/ingress-nginx-admission-create. Approach: Following the official docs example, add to the admission webhook Job in values argocd.argoproj.io/hook: Skip (or upgrade the chart to a version that uses a certificate controller). Limitation: After skipping, make sure the webhook certificate is generated some other way.
Case 3: cross-application order (platform components before business apps)
Problem: In App of Apps, cert-manager must be ready before the business applications that use Certificate. Approach: In the root application, set sync-wave on the child Applications (cert-manager -1, business apps 0), and in argocd-cm restore argoproj.io/Application the health check (Module 5), otherwise the parent application cannot wait for child applications to be “healthy”. Limitation: Only takes effect when the root application syncs; automatic syncs of child applications afterwards are independent.
Common errors and fixes
waiting for completion of hook batch/Job/db-migrate (sync stays Running for a long time)
Cause: The hook Job is still running, the Pod is Pending (image pull, insufficient resources), or it is stuck retrying.
kubectl -n hooks-demo describe job db-migrate | tail -15 kubectl -n hooks-demo get pods -l job-name=db-migrate kubectl -n hooks-demo logs job/db-migrate
Fix: Fix the Job; if needed, argocd app terminate-op hooks-demo , then sync again. Set a reasonable backoffLimit and activeDeadlineSeconds, to avoid waiting forever.
waiting for healthy state of apps/Deployment/web (PostSync never runs)
Cause: PostSync only runs after all resources are Healthy; the Deployment rollout has not finished (probe failures, wrong image).
argocd app get hooks-demo | grep -v Healthy kubectl -n hooks-demo rollout status deploy/web --timeout=30s kubectl -n hooks-demo get events --sort-by=.lastTimestamp | tail
Fix: Resolve the workload problem. If a resource’s health assessment is unreasonable (a custom CR stays Progressing forever), correct it with the custom health check from Module 5.
Job.batch "db-migrate" is invalid: spec.template: Invalid value: ... field is immutable
Cause: A fixed-name hook was not deleted (the policy was explicitly set to HookSucceeded but the last run failed, so the Job was kept). The new template cannot be applied onto the old Job.
Fix: Add to the deletion policy BeforeHookCreation (can be comma-combined with other policies), or manually delete the old Job.
Helm chart’s pre-upgrade hook did not run
Cause: The chart contains Argo CD hook annotations at the same time (once any Argo CD hook is defined, all Helm hooks are ignored); or it uses an unsupported hook (pre-rollback, test).
argocd app manifests APP | grep -nE 'helm.sh/hook|argocd.argoproj.io/hook'
Fix: Use only one kind of annotation; confirm the mapping (pre-install/pre-upgrade → PreSync).
The hook Job has disappeared, but the sync still shows it waiting for the hook
Cause: The Job has ttlSecondsAfterFinished, and Kubernetes deleted it before Argo CD read the result; or someone deleted it manually and removed the finalizer.
Fix: Remove the TTL and use hook-delete-policy; terminate the operation and sync again.
1. List the wave and hook annotations of all resources in the hooks-demo rendered output.
argocd app manifests hooks-demo | grep -E '^kind:|^ name:|sync-wave|argocd.argoproj.io/hook'
2. The sync is stuck on a hook; terminate the current operation and view the result.
argocd app terminate-op hooks-demo argocd app get hooks-demo --show-operation | head
An application contains a Secret db-cred (wave 0) and a PreSync migration Job (reads db-cred). On the first deployment the migration fails, and the second sync succeeds. What is the cause? How should it be changed?
The PreSync phase runs before the whole Sync phase. On the first deployment the Secret has not been created yet, so the Job cannot read it; on the second sync the Secret was created by the previous, partially completed sync (or, after a password rotation, the Job reads the old value). Fix: keep the credentials outside the application (provided by ESO or a platform application), or declare the Secret itself as a PreSync hook with a lower wave (such as -1), so it is created before the migration Job.
Verified teaching videos
Official docs
Video storyboard script (about 100 seconds)
These course materials cannot directly generate video/MP3; the storyboard and narration script are provided and can be handed to a video tool.
Visual: three swim lanes, PreSync, Sync and PostSync, with one red SyncFail swim lane below.
Narration: a sync runs in phases: first PreSync, then Sync, finally PostSync. If any step fails, SyncFail runs.
Visual: in the Sync lane, resource cards are arranged into three columns by wave −1, 0 and 1, with a two-second hourglass appearing between columns.
Narration: within a phase, waves run from lowest to highest. Each wave waits for its resources to become healthy, then waits the default two seconds before the next wave starts.
Visual: the db-migrate Job runs and its progress bar fills and turns green; then the Deployment rolls out; finally the smoke-test Job runs.
Narration: the database migration goes in PreSync and the smoke test goes in PostSync. PostSync starts only when all resources are healthy.
Visual: smoke-test turns red, the notify-failure Job appears and sends an alert; a label shows that hooks that succeed are deleted by HookSucceeded, while failed ones are kept.
Narration: a smoke-test failure triggers the SyncFail alert. Use deletion policies to control hook retention: delete the successful ones and keep the failed ones for troubleshooting.
Module 5 · Health checks: built-in assessment and custom Lua
- State the built-in health assessments: Deployment/StatefulSet/DaemonSet/ReplicaSet (observedGeneration and updated replica count), Service (LoadBalancer needs an ingress address), Ingress, PVC (Bound), Job, CronJob, Pod, etc.
- State the Application health aggregation rule: take the worst status among its direct child resources. The order is Healthy → Suspended → Progressing → Missing → Degraded → Unknown.
- Use
resource.customizations.health.<group>_<kind>to write a Lua health check (delivered through the Helm valuesconfigs.cm), and useargocd admin settings resource-overrides healthto test it locally.
What: health states and built-in assessment
| State | Meaning | Example |
|---|---|---|
| Healthy | Healthy | All Deployment replicas are updated and available |
| Progressing | Not yet healthy but progressing (also the default for custom checks) | Rolling update in progress, Job running |
| Degraded | Failed or degraded | Deployment past progressDeadlineSeconds, CronJob’s most recent run failed |
| Suspended | Paused, waiting for an external event | Paused CronJob / Deployment, or suspend: true the suspended Job |
| Missing | Present in Git, not in the cluster | Resource not yet synced |
| Unknown | Health assessment failed | Lua script error |
| Resource | Key built-in assessment points (official docs) |
|---|---|
| Deployment / ReplicaSet / StatefulSet / DaemonSet | observedGeneration equals generation; updated replica count equals desired replica count |
| Service | When the type is LoadBalancer, status.loadBalancer.ingress is non-empty (stays Progressing forever when the kind has no LB controller) |
| Ingress | status.loadBalancer.ingress is non-empty |
| PersistentVolumeClaim | status.phase is Bound |
| Job / CronJob | Job suspended → Suspended; CronJob’s most recent Job failed → Degraded, running → Progressing |
| Pod | restartPolicy: Always Healthy once ready; Never/OnFailure is treated as “run to completion”; while running it is Progressing (can be changed with argocd.argoproj.io/ignore-restart-policy: "true" ) |
| argoproj.io/Application | Since 1.8,removed; App of Apps must restore it in argocd-cm, following the official example |
| Many CRDs (cert-manager, Rollout, Crossplane, etc.) | The Argo CD repository resource_customizations/ contains built-in Lua scripts that grow with each version |
Why: what health assessment affects
- Sync orchestration: every wave waits for health; PostSync waits for all resources to be Healthy (Module 4). A CR that stays Progressing forever will make the sync wait forever.
- App of Apps and progressive sync: parent applications and ApplicationSet RollingSync both depend on child application health (Hour 3).
- Alerts and notifications: the Notifications
on-health-degradedtriggers and metricsargocd_app_info{health_status=…}(Hours 6 and 7).
How: Lua custom health checks
In the script, the global variable obj is the resource object; the script returns a table: status (Healthy / Progressing / Degraded / Suspended) and an optional message. The key name format is resource.customizations.health.<group>_<kind>; for core-group resources (Pod, PVC) omit the group prefix. For security reasons the Lua standard library is disabled by default and can be enabled with resource.customizations.useOpenLibs.<group>_<kind>: "true" .
configs:
cm:
resource.customizations.health.example.com_Widget: |
hs = {}
if obj.status ~= nil and obj.status.conditions ~= nil then
for i, c in ipairs(obj.status.conditions) do
if c.type == "Ready" and c.status == "True" then
hs.status = "Healthy"
hs.message = c.message
return hs
end
if c.type == "Ready" and c.status == "False" and c.reason == "Failed" then
hs.status = "Degraded"
hs.message = c.message
return hs
end
end
end
hs.status = "Progressing"
hs.message = "Waiting for Ready condition"
return hs
To reuse the same script for a group of CRDs, use the resource.customizations key with a wildcard (for example "*.aws.crossplane.io/*"); resource.customizations.health.* keys written separately do not support wildcards (ConfigMap keys do not allow *). Configured checks take precedence over the built-in Go checks, so they can also override default assessments for Deployment, Ingress, etc. From v3.6 the script can also return deletionMessage, during resource deletion (when a deletionTimestamp) to explain which finalizer it is waiting for.
When: when to customize
- An in-house Operator’s CR has no built-in check → you must write one; otherwise you only see empty health or it never blocks (not blocking is equally dangerous: later waves may start before the CR is ready).
- The built-in check does not fit the environment (for example, a LoadBalancer Service in kind stays Progressing forever) → override the check, or use ClusterIP in the lab.
- Do not want a child resource to affect application health → add
argocd.argoproj.io/ignore-healthcheck: "true".
.status.resources[].health in order to read each resource’s health” — in v3 it is no longer persisted to the CR by default (resourceHealthSource: appTree), so use argocd app get -o json or the API; it can be restored via controller.resource.health.persist: "true" to restore the old behavior. ④ “If one resource is Missing, the application is Missing” — from v3.4, the application is Missing only when all resources are missing.Architecture diagram: where health state is computed
Decision diagram: Widget’s Lua assessment
Interactive: application health aggregation + Lua assessor
Left: adjust each child resource’s health state and see how application health takes the worst value (you can tick “ignore health”). Right: choose the Widget’s status and run the Lua assessment (the browser simulates the same logic line by line in JavaScript); the execution trace appears below.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
argocd admin settings resource-overrides health RESOURCE.yaml --argocd-cm-path argocd-cm.yaml | Test a Lua health check offline | No connection to Argo CD is needed; you can also --load-cluster-settings read argocd-cm from the cluster |
argocd app get APP -o json | jq '.status.health' | View application health | For resource-level health see argocd app resources APP or the UI |
argocd app wait APP --health --timeout N | Wait for the application to be Healthy (common in CI) | Exits with an error when Degraded |
kubectl patch … --subresource=status | Manually modify a CR’s status in the lab | the CRD must enable the status subresource |
Test Lua locally (test before going live)
mkdir -p /tmp/health && cd /tmp/health
kubectl -n argocd get cm argocd-cm -o yaml > argocd-cm.yaml # or hand-write a ConfigMap containing only that key
cat > widget.yaml <<'EOF'
apiVersion: example.com/v1alpha1
kind: Widget
metadata:
name: demo
status:
conditions:
- type: Ready
status: "False"
reason: Failed
message: quota exceeded
EOF
argocd admin settings resource-overrides health ./widget.yaml --argocd-cm-path ./argocd-cm.yaml
STATUS: Degraded MESSAGE: quota exceeded
Common errors: The key name is written as example.com/Widget (should be an underscore example.com_Widget); wrong YAML block indentation truncates the script; using os/string library in the script without enabling useOpenLibs. Production use: Keep the Lua and test YAML in Git, and in CI run the command against each sample and assert the results.
Lab: write a health check for a self-built CRD Widget
widgets.example.com and a Widget, and create the application widgets; first observe the behavior without a health check, then deliver a Lua check through Argo CD Helm values, and use kubectl patch --subresource=status to simulate a controller updating the status. There is no real controller, so there are no external actions.cd ~/gitops-lab/apps/widgets
cat > crd.yaml <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: widgets.example.com
spec:
group: example.com
scope: Namespaced
names: {plural: widgets, singular: widget, kind: Widget}
versions:
- name: v1alpha1
served: true
storage: true
subresources:
status: {}
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
size: {type: string}
status:
type: object
x-kubernetes-preserve-unknown-fields: true
EOF
cat > demo.yaml <<'EOF'
apiVersion: example.com/v1alpha1
kind: Widget
metadata:
name: demo
spec:
size: small
EOF
cat > ~/gitops-lab/argocd/apps/widgets.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: widgets
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
path: apps/widgets
destination:
server: https://kubernetes.default.svc
namespace: widgets
syncPolicy:
syncOptions:
- CreateNamespace=true
- ServerSideApply=true
EOF
cd ~/gitops-lab && git add -A && git commit -m "widgets: CRD + demo" && git push
kubectl apply -f argocd/apps/widgets.yaml
argocd app sync widgets
argocd app get widgets | tail -4
GROUP KIND NAMESPACE NAME STATUS HEALTH ... apiextensions.k8s.io CustomResourceDefinition widgets.example.com Synced example.com Widget widgets demo Synced
When the CRD and CR are in the same sync, Argo CD creates the CRD first by kind ordering and automatically skips the CR’s dry-run. The Widget has no health state, so application health is unaffected by it. This means later waves will not wait for it to become ready.
resource.customizations.health.example.com_Widget from the Principle page, append to ~/gitops-lab/bootstrap/argocd-values.yaml ’s configs.cm under (mind the indentation), then:
helm upgrade argocd argo/argo-cd -n argocd --version 10.18.0 \
-f ~/gitops-lab/bootstrap/argocd-values.yaml --wait --timeout 10m
kubectl -n argocd get cm argocd-cm -o jsonpath='{.data.resource\.customizations\.health\.example\.com_Widget}' | head -3
argocd app get widgets --refresh | grep Widget
hs = {}
if obj.status ~= nil and obj.status.conditions ~= nil then
for i, c in ipairs(obj.status.conditions) do
example.com Widget widgets demo Synced Progressing Waiting for Ready conditionkubectl -n widgets patch widget demo --subresource=status --type=merge \
-p '{"status":{"conditions":[{"type":"Ready","status":"True","message":"provisioned"}]}}'
sleep 5; argocd app get widgets | grep -E 'Health Status|Widget'
kubectl -n widgets patch widget demo --subresource=status --type=merge \
-p '{"status":{"conditions":[{"type":"Ready","status":"False","reason":"Failed","message":"quota exceeded"}]}}'
sleep 5; argocd app get widgets | grep -E 'Health Status|Widget'
Health Status: Healthy example.com Widget widgets demo Synced Healthy provisioned Health Status: Degraded example.com Widget widgets demo Synced Degraded quota exceeded
In v3, status field differences and resource updates are ignored by default, but the official docs state that health changes are still reported. So the status update is reflected in health, and the application remains Synced.
argocd.argoproj.io/ignore-healthcheck: "true" and push and sync; application health returns to Healthy, and the Widget no longer participates in aggregation.argocd app delete widgets --yes. Deleting the CRD cascades to delete all Widgets, which is acceptable in a lab cluster; to keep the CRD, first add Delete=false. Finally kubectl delete ns widgets.Case 1: unified health checks for Crossplane resources
Problem: Dozens of *.aws.crossplane.io resources; writing keys one by one is costly to maintain. Approach: In resource.customizations use a wildcard "*.aws.crossplane.io/*" to configure one check based on Ready/Synced conditions health.lua. Limitation: Wildcards can only be used in the resource.customizations key; GVK keys that start with a wildcard must be quoted.
Case 2: App of Apps waves do not take effect
Problem: The root application set waves on child Applications, but the second wave started without waiting for the first wave’s child applications to be healthy. Approach: Following the official docs, in argocd-cm add resource.customizations.health.argoproj.io_Application (reads obj.status.health.status). Limitation: In v3, per-resource health is not persisted in the Application CR by default, but the application’s overall status.health still exists, and this script can use it.
Case 3: LoadBalancer Service stays Progressing forever
Problem: The local or private cloud cluster has no LB controller,type: LoadBalancer so the Service has no address, the application stays Progressing, and the PostSync smoke test never runs. Approach: Deploy MetalLB / cloud-provider-kind, or change it to NodePort/ClusterIP in that environment’s overlay. Do not change the Service health check to always Healthy just to make it turn green.
Common errors and fixes
Health Status: Unknown — failed to get resource health for "Widget" ... : <string>:3: attempt to index a nil value
Cause: The Lua script accesses it without a nil check obj.status.conditions.
Fix: Check every level ~= nil; use argocd admin settings resource-overrides health to test the “no status” sample.
The custom health check has no effect at all; the resource still has no health state
Cause: Wrong key name (used / instead of _; a core-group resource has an extra group prefix; case mismatch); or the ConfigMap was not updated (Helm values indentation is wrong).
kubectl -n argocd get cm argocd-cm -o json | jq -r '.data | keys[] | select(startswith("resource.customizations"))'
Fix: Correct the key name to resource.customizations.health.<group>_<Kind>; after the change, run argocd app get APP --hard-refresh.
Application stays Progressing: Service web Progressing Waiting for ... load balancer
Cause: The LoadBalancer Service has no external address (kind has no LB controller).
Fix: Use ClusterIP in the lab; or install cloud-provider-kind / MetalLB.
Deployment shows Degraded: Deployment "web" exceeded its progress deadline
Cause: The rolling update did not complete within progressDeadlineSeconds (default 600s): image pull failures, probe failures, insufficient resources.
kubectl -n NS rollout status deploy/web --timeout=10s kubectl -n NS get pods -l app=web kubectl -n NS describe pod POD | tail -20
Fix: Fix the workload and push a new commit; for fast recovery, use argocd app rollback (the application must not have automated sync enabled) or a Git revert (Hour 1).
Calling string.find in a Lua script errors: attempt to index a nil value (global 'string')
Cause: The Lua standard library is disabled by default.
Fix: Set for this type resource.customizations.useOpenLibs.<group>_<kind>: "true", or rewrite the logic so it does not depend on the standard library.
1. List the resource types that have custom health checks in argocd-cm.
kubectl -n argocd get cm argocd-cm -o json | jq -r '.data | keys[] | select(startswith("resource.customizations.health."))' | sed 's/resource.customizations.health.//'2. In CI, after deployment, wait up to 5 minutes for the application to be healthy; if it fails, print the operation details.
argocd app wait myapp-dev --health --timeout 300 || { argocd app get myapp-dev --show-operation; exit 1; }A team’s Operator creates Database CR; Argo CD shows Synced, but the subsequent application Deployment starts and crashes while the database is not ready. How can this be improved?
The Database has no health check, so Argo CD does not wait for it. ① Write a Lua health check for <group>_Database (based on the Ready condition and observedGeneration); ② put Database in wave -1 and Deployment in wave 0, so the waves wait for Database to be Healthy; ③ the application itself should still implement startup retries and not rely only on orchestration.
Verified teaching videos
No verified English video dedicated to “Lua custom health checks” was found; refer to the official docs and storyboard script below.
Official docs
Video storyboard script (about 90 seconds)
These course materials cannot directly generate video/MP3; the storyboard and narration script are provided and can be handed to a video tool.
Visual: a green Synced badge next to a red Degraded badge.
Narration: sync status only says the cluster matches Git; health status says whether it is actually working.
Visual: six states arranged in a column from best to worst; the application card shows the worst one.
Narration: application health takes the worst state among direct child resources. The order is Healthy, Suspended, Progressing, Missing, Degraded, Unknown.
Visual: a Lua snippet is highlighted line by line; obj.status.conditions is read and returns Healthy.
Narration: for custom resources, a Lua script reads the status conditions and returns a health state and message; by default it returns Progressing rather than Healthy.
Visual: the terminal runs argocd admin settings resource-overrides health, with output STATUS Degraded.
Narration: before going live, test the script locally with the argocd admin command.
Module 6 · ignoreDifferences and diff customization
- Describe the fields to ignore in three ways:
jsonPointers(RFC 6902 paths),jqPathExpressions(select list elements by content),managedFieldsManagers(by field manager). - Distinguish application-level
spec.ignoreDifferences, system-levelresource.customizations.ignoreDifferences.<group>_<kind>/.all, and resource annotationsargocd.argoproj.io/ignore-differences. - Understand that “ignoring differences only affects comparison, not sync”. To keep the live values of ignored fields during sync, you need
RespectIgnoreDifferences=trueto preserve the live values of ignored fields during sync.
What: how differences arise
Before Argo CD compares “desired state (rendered result)” with “live state”, it first performs normalization: strip status (v3 does this for all resources by default), normalize numeric formats by known types, apply ignoreDifferences rules… The remaining differences determine whether the application is OutOfSync. Common sources of “false positives” (listed in the official docs):
- A controller or mutating webhook modifies it after the object is submitted (injects initContainers, fills in caBundle, adds default values).
- HPA changed
spec.replicas; the HPA controller also reordersspec.metricsentries in that list. - A Helm template uses
randAlphaNumrandom functions such as that, which produce different output on every render. - The manifest has extra fields the API does not recognize (dropped by the API server, so they are “missing” forever).
Why: why you cannot simply “ignore everything”
Each ignored field removes one drift-detection point: even if someone manually breaks an ignored field, Argo CD will not alert (and selfHeal will not repair it). So the principle is: fix the root cause first (remove from Git the fields managed by others, write metrics in the order the controller uses, and assign random values explicitly),then ignore precisely (scope by group/kind/name/namespace, using the smallest path).
How: three syntaxes
spec:
ignoreDifferences:
# 1) JSON Pointer: exact path; write / inside a path as ~1
- group: apps
kind: Deployment
name: podinfo # optional: scope by name
namespace: podinfo-dev # optional: scope by namespace
jsonPointers:
- /spec/replicas
# 2) jq path expression: select list elements by content
- group: apps
kind: Deployment
jqPathExpressions:
- .spec.template.spec.initContainers[] | select(.name == "injected-init-container")
# 3) field manager: ignore all fields owned by a manager
- group: "*"
kind: "*"
managedFieldsManagers:
- kube-controller-manager
syncPolicy:
syncOptions:
- RespectIgnoreDifferences=true # do not overwrite these fields during sync either
| Level | Where it is written | Supports | Suited for |
|---|---|---|---|
| Application-level | Application.spec.ignoreDifferences | All three syntaxes supported; can be scoped by name/namespace | Special cases for one application (a Deployment managed by an HPA) |
| System-level | argocd-cm: resource.customizations.ignoreDifferences.<group>_<kind>, or .all | all three syntaxes | Known problems that are common across the cluster (webhook caBundle, kube-controller-manager) |
| Resource annotation | On the resource, the argocd.argoproj.io/ignore-differences | supports only jsonPointers; combined (union) with application-level rules | When the application team has no permission to modify the Application |
v3 default changes
resource.compareoptions’signoreResourceStatusFielddefault changes fromcrdtoall: the status field of all resources is excluded from comparison.- System-level ignoreDifferences is also used by default to ignore “resource update events” (
ignoreDifferencesOnResourceUpdates: true), reducing controller load; the chart also configures by defaultresource.customizations.ignoreResourceUpdates.all: /status. - v3.6: applications with SSA enabled use Server-Side Diff— the API server computes “what it will look like after apply” in dry-run mode, predicting default values and webhook changes more accurately, so many false positives naturally disappear.
When: which to choose
| Situation | Preferred approach | Next best |
|---|---|---|
| HPA manages the replica count | Remove from the Git manifest spec.replicas | jsonPointers /spec/replicas + RespectIgnoreDifferences |
| webhook injects initContainer / sidecar | Enable SSA (Server-Side Diff includes the effect of the webhook) | jqPathExpressions selects the injected container by name |
| controller fills in caBundle | System-level jq: .webhooks[]?.clientConfig.caBundle | — |
| multiple controllers write the same object | managedFieldsManagers specifies the controller name | — |
| Helm random values | provide the value explicitly in values | do not ignore the entire Secret data |
RespectIgnoreDifferences=true, and this option does not apply to newly created resources. ② “Writing group as apps/v1” — the group does not include a version; write apps; the core group uses an empty string or omits it. ③ “Resource annotations can also use jq” — annotations support only jsonPointers. ④ “IgnoreExtraneous is also field-level ignoring” — no: argocd.argoproj.io/compare-options: IgnoreExtraneous it is the option that makes resources not present in Git (such as generated resources) not affect sync status; it differs from field-level ignoring.Flow chart: from the raw object to sync status
Sequence diagram: the “tug-of-war” without RespectIgnoreDifferences
Interactive: diff normalization simulator
On the left is the desired Deployment rendered from Git; on the right is the live Deployment in the cluster (HPA changed the replica count, a webhook injected an initContainer, the controller wrote status). Tick different rules to see the remaining differences and sync status; then click “Sync” to see whether the live values are kept.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
argocd app diff APP | Show the differences between desired and live (after normalization) | --refresh/--hard-refresh,--server-side-diff,--exit-code (non-zero when there are differences),--local |
argocd admin settings resource-overrides ignore-differences RES.yaml --argocd-cm-path cm.yaml | Test system-level ignore rules offline | Print which fields will be ignored |
kubectl get … --show-managed-fields -o yaml | Find field manager names | Use a name for managedFieldsManagers |
argocd app patch APP --type merge --patch … | Temporarily modify an Application (e.g., add ignoreDifferences) | when managing declaratively, change Git |
1) Find out who changed the replica count
kubectl -n podinfo-dev get deploy podinfo --show-managed-fields -o json \ | jq -r '.metadata.managedFields[] | select(.fieldsV1."f:spec"."f:replicas" != null) | "\(.manager) \(.operation) \(.subresource // "")"'
kube-controller-manager Update scale
The HPA changes it via scale the subresource to change the replica count; the manager name is kube-controller-manager; manual kubectl scale changes are under the manager name kubectl.
2) Test whether the jq expression matches
kubectl -n podinfo-dev get deploy podinfo -o json | jq '.spec.template.spec.initContainers[]? | select(.name == "injected-init")'
Argo CD uses gojq, whose syntax is largely the same as jq; locally, verify with jq that the expression selects the target.
3) Check in CI whether “drift remains after deployment”
argocd app diff podinfo-dev --refresh --exit-code; echo "diff exit=$?"
Lab: HPA changing the replica count no longer causes drift
replicas: 1 value in Git (the “tug-of-war”), then fix it in two ways. When the current replica count is below minReplicas, the HPA scales straight up to minReplicas; first install metrics-server per Step 4 of the warm-up, otherwise the HPA’s health may not be Healthy.cd ~/gitops-lab/apps/podinfo/overlays/dev
cat > hpa.yaml <<'EOF'
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: podinfo
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: podinfo
minReplicas: 2
maxReplicas: 4
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 80
EOF
sed -i 's#^- ../../base#- ../../base\n- hpa.yaml#' kustomization.yaml
kubectl kustomize . | grep -E '^kind:|replicas:'
git add -A && git commit -m "dev: add HPA (min 2)" && git push
argocd app sync podinfo-dev
# watch the tug-of-war: replica count bouncing between 1 and 2
kubectl -n podinfo-dev get deploy podinfo -w
NAME READY UP-TO-DATE AVAILABLE AGE podinfo 1/1 1 1 2d podinfo 1/2 1 1 2d ← HPA scales to 2 podinfo 1/1 1 1 2d ← selfHeal reverts to 1 podinfo 1/2 2 1 2d ← HPA scales to 2 again …
replicas: block in the dev overlay (the replicas: 1 in base must also be removed, or use a JSON patch in the dev overlay remove /spec/replicas).
cat >> kustomization.yaml <<'EOF'
- target:
kind: Deployment
name: podinfo
patch: |-
- op: remove
path: /spec/replicas
EOF
# also remove the replicas: section (two lines), then check
sed -i '/^replicas:/,/count: 1/d' kustomization.yaml
kubectl kustomize . | grep -c 'replicas:' # expected output 0 (the HPA’s minReplicas/maxReplicas do not match this pattern)
Note: an appended patch must be placed under the existing patches: list (in the Hour 1 dev overlay, patches is the last key, so simply append). If the grep result is not 0, check kustomization.yaml in an editor. Under SSA, Git no longer contains the replicas field, Argo CD no longer owns it, and the HPA has exclusive control of the field.
git revert to revert Fix A, then in argocd/apps/podinfo-dev.yaml add:
spec:
ignoreDifferences:
- group: apps
kind: Deployment
name: podinfo
jsonPointers:
- /spec/replicas
syncPolicy:
syncOptions:
- CreateNamespace=true
- ServerSideApply=true
- PruneLast=true
- RespectIgnoreDifferences=true
cd ~/gitops-lab && git add -A && git commit -m "podinfo-dev: ignore replicas" && git push kubectl apply -n argocd -f argocd/apps/podinfo-dev.yaml argocd app get podinfo-dev --refresh | grep -E 'Sync Status|Deployment' kubectl -n podinfo-dev get deploy podinfo
Sync Status: Synced to main (5d1a7c2) apps Deployment podinfo-dev podinfo Synced Healthy NAME READY UP-TO-DATE AVAILABLE AGE podinfo 2/2 2 2 2d
kubectl -n podinfo-dev scale deploy podinfo --replicas=4, and the application still shows Synced (drift is no longer detected); the HPA will bring it back within range in the next cycle. This is “the more you ignore, the bigger the blind spot”.Case 1: Istio / Linkerd injection causes false positives
Problem: After enabling sidecar injection, some Deployments (whose templates carry injection-related annotations) stay OutOfSync. Approach: First enable SSA (v3.6 automatically uses Server-Side Diff, so webhook changes are included in the prediction); if residual differences remain, use jqPathExpressions to precisely ignore the injected container or annotations. Limitation: Server-Side Diff is not run for newly created resources; on first creation the webhook is not part of the diff.
Case 2: cert-manager injects caBundle
Problem: The caBundle of a ValidatingWebhookConfiguration is written by cainjector, Git has it empty, and every cluster shows OutOfSync. Approach: Use a system-level resource.customizations.ignoreDifferences.admissionregistration.k8s.io_ValidatingWebhookConfiguration,jqPathExpressions: ['.webhooks[]?.clientConfig.caBundle'], and distribute it via the argo-cd chart’s configs.cm setting to all Argo CD instances.
Case 3: HPA reorders metrics
Problem: An HPA with both CPU and memory metrics stays OutOfSync forever. Approach: The official docs identify the root cause as the HPA controller reordering spec.metrics; write them in Git in the controller’s order, with no need to ignore anything. Limitation: The order may change across Kubernetes versions; re-check after upgrades.
Common errors and fixes
The application goes OutOfSync right after sync; the diff shows only /spec/replicas differs
Cause: An HPA or another controller manages the replica count, while Git still declares replicas.
argocd app diff APP kubectl get hpa -A
Fix: Remove replicas from Git, or use ignoreDifferences + RespectIgnoreDifferences.
JQ patch execution timed out (1s)
Cause: The jq expression is too complex or the object is very large, and the default timeout is 1 second.
Fix: Simplify the expression; if needed, in argocd-cmd-params-cm set ignore.normalizer.jq.timeout: "5s" (chart: configs.params), then restart the controller.
ignoreDifferences is configured, but the diff still shows the field
Cause: group written with a version (apps/v1), wrong kind capitalization, name/namespace scoping does not match, and the “/” in the JSON Pointer / not escaped as ~1.
kubectl -n argocd get application APP -o jsonpath='{.spec.ignoreDifferences}' | jq .
Fix: Correct group/kind; for an annotation key path, for example /metadata/annotations/example.com~1rev.
RespectIgnoreDifferences is set, but in a newly deployed environment the replica count is still the Git value
Cause: This option only patches the desired state with live values when the resource already exists; for newly created resources the field is written as usual.
Fix: This is expected behavior; the HPA takes over afterwards. If you do not want it written, remove the field from Git.
After upgrading to v3, applications that depend on the status field no longer show differences
Cause: v3 by default ignoreResourceStatusField: all.
Fix: In the argocd-cm Application’s resource.compareoptions setting, crd to restore v2 behavior (the official docs do not recommend treating status as desired state).
1. Use the argocd CLI to temporarily append ignoreDifferences for podinfo-dev (ignore the Deployment’s /spec/replicas).
argocd app patch podinfo-dev --type merge --patch '{"spec":{"ignoreDifferences":[{"group":"apps","kind":"Deployment","jsonPointers":["/spec/replicas"]}]}}'A merge patch replaces the whole ignoreDifferences list; when managing declaratively, change Git.
2. Write the system-level configuration that ignores the caBundle of all MutatingWebhookConfigurations (in Helm values form).
configs:
cm:
resource.customizations.ignoreDifferences.admissionregistration.k8s.io_MutatingWebhookConfiguration: |
jqPathExpressions:
- '.webhooks[]?.clientConfig.caBundle'To stop OutOfSync, a colleague added to the system-level .all configuration: jsonPointers: [/spec]. What are the consequences? What should be done?
The entire spec of all resources is no longer compared: no manual change, and not even a change in Git, shows as OutOfSync, automated sync is never triggered, so GitOps effectively stops working. Roll back this configuration, and use argocd app diff to find the specific fields and their sources (managedFields), then ignore precisely by resource type and name, or fix the root cause.
Verified teaching videos
Official docs
Video storyboard script (about 80 seconds)
These course materials cannot directly generate video/MP3; the storyboard and narration script are provided and can be handed to a video tool.
Visual: the HPA and Argo CD, two hands, turn the replica-count knob back and forth; Pods keep appearing and disappearing.
Narration: the HPA changes the replica count, Argo CD changes it back to the Git value, and this is the tug-of-war.
Visual: two YAML files side by side; the replicas line is covered by a translucent mask; status changes from OutOfSync to Synced.
Narration: ignoreDifferences removes the specified fields before comparison, so the comparison result no longer includes them.
Visual: the sync button is pressed; the replicas field is not reverted; a label beside it reads RespectIgnoreDifferences.
Narration: to also keep sync from changing this field, you must turn on RespectIgnoreDifferences.
Visual: under a magnifier, an ignored field is manually broken, yet there is no alert at all.
Narration: every ignored field adds a blind spot, so fix the root cause first, for example by removing from Git the fields managed by the HPA.
Module 7 · Resource tracking methods: annotation and label
- Name the three tracking methods:
annotation(v3 default),annotation+label,label, and the configuration keyapplication.resourceTrackingMethod(argocd-cm). - Read a tracking-id:
<app name>:<group>/<kind>:<namespace>/<name>, and understand that “non-self-referencing annotations” are ignored. - Know the risks of label mode (63-character truncation, being copied or written by other tools), the default in the argo-cd chart
application.instanceLabelKey: argocd.argoproj.io/instance, and theinstallationIDsetting for multiple instances, plus v2 → v3 migration considerations.
What: three tracking methods
| Method | Metadata written to the resource | How ownership is determined | Applies to |
|---|---|---|---|
annotation (v3 default) | Annotation argocd.argoproj.io/tracking-id: podinfo-dev:apps/Deployment:podinfo-dev/podinfo | Annotation, and the annotation value must point to the resource itself | The vast majority of cases |
annotation+label | The annotation above + an instance label (value is the app name; over 63 characters gets truncated) | Annotation only; the label is only for other tools to recognize | Needs compatibility with tools that query by label |
label | Instance label (upstream default key app.kubernetes.io/instance, can be application.instanceLabelKey customized) | label value = app name | v2 environments not yet ready to migrate |
configs.cm."application.instanceLabelKey": argocd.argoproj.io/instance (not the upstream default app.kubernetes.io/instance); the Hour 1 values explicitly set application.resourceTrackingMethod: annotation. So in this lesson’s cluster, by default you see the tracking-id annotation; if you switch to annotation+label, the label key that appears is argocd.argoproj.io/instance. This also explains why the myapp app.kubernetes.io/instance=myapp label (generated by the Helm template) is unrelated to Argo CD.Why: problems with label mode
- 63-character limit: long application names (especially those generated by ApplicationSet
team-a-myapp-prod-eastus2, etc.) get truncated and may collide. - Labels written by others: many Helm charts and Operators put
app.kubernetes.io/instanceon the resources they generate, and Argo CD will treat these resources that it did not deploy as its own, so they appear as “extra resources” and may be pruned when prune is on. - Labels copied: when a controller copies an object (for example, a tool that copies Secrets into other namespaces), the labels are copied along with it, and the copy is also claimed.
- Multiple instances: when multiple Argo CD instances in the same cluster manage same-named applications, they cannot tell them apart.
annotation mode solves the copy problem through a “self-reference” check: the tracking-id records group/kind/namespace/name; if the annotation does not point to the resource itself (for example, it was copied to another namespace), Argo CD does not count it in the application’s sync status and does not prune it (the UI shows it at the top level, with no sync status).
How: configuration and multiple instances
# ~/gitops-lab/bootstrap/argocd-values.yaml (argo-cd chart)
configs:
cm:
application.resourceTrackingMethod: annotation # or annotation+label / label
application.instanceLabelKey: argocd.argoproj.io/instance # chart default; used by the label-related modes
installationID: lab-main # set when multiple Argo CD instances manage the same cluster; resources get one extra annotation
# argocd.argoproj.io/installation-id: lab-main
In a tracking-id, the core group is empty (such as podinfo-dev:/Service:podinfo-dev/podinfo); for cluster-scoped resources, the namespace part takes the Application’s spec.destination.namespace (see the official upgrade notes). Building tracking metadata by hand is not an officially supported feature.
When: v2 → v3 migration key points (official upgrade notes)
- Detection:
kubectl get cm argocd-cm -n argocd -o jsonpath='{.data.application\.resourceTrackingMethod}'is empty orlabelmeans you are affected. - Most users can upgrade directly: at the next sync the label is replaced with an annotation, and a missing label does not cause OutOfSync; but the annotation only appears after a new commit or an explicit sync.
- Edge case: if the first sync after switching happens to include deleting a resource, Argo CD cannot recognize that it belongs to the application and will not delete it (creating an orphan). Run a sync for all applications after upgrading.
- For applications using
ApplyOutOfSyncOnly=trueand tracked by label before, after upgrading you must explicitly run one sync without (untick it in the UI, or call the API). - Not migrating yet: set
application.resourceTrackingMethod: label, as the official docs have no plan to remove label mode.
app.kubernetes.io/instance ① “A label is Argo CD’s tracking label” — in the v3 default mode it is not; in this lesson’s chart the label key is also argocd.argoproj.io/instance. ② “Namespaces created by CreateNamespace carry tracking information” — by default they do not, and deleting the application does not delete the namespace. ③ “Manually adding a tracking-id to a resource brings it under management with no side effects” — if the resource is not in Git, it becomes an “extra resource” and is deleted when prune is enabled (reproduced in the lab). ④ “Switching the tracking method immediately rewrites all resources” — new metadata is only written during sync.Decision diagram: whether an object belongs to application podinfo-dev
Comparison diagram: the same copied object
Resolver: “Who does this resource belong to?”
Choose a tracking method and an object scenario to simulate the application-controller’s decision process: which metadata is read, whether it belongs to podinfo-dev, whether it takes part in the diff, and whether, with automated.prune enabled, it gets deleted.
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
kubectl get cm argocd-cm -n argocd -o jsonpath='{.data.application\.resourceTrackingMethod}' | View the tracking method | An empty value equals annotation in v3 |
kubectl get … -o jsonpath='{.metadata.annotations.argocd\.argoproj\.io/tracking-id}' | View a resource’s tracking-id | dots in the jsonpath must be escaped |
argocd app resources APP --orphaned | List “orphan” resources in a namespace that do not belong to any application | requires orphaned resource monitoring to be enabled in the AppProject (Hour 4) |
argocd app sync APP | Write new metadata after switching the tracking method | after upgrading, it is recommended to sync all applications once |
1) List all resources in a namespace and the applications they belong to
kubectl -n podinfo-dev get deploy,svc,cm,hpa -o json \ | jq -r '.items[] | [.kind, .metadata.name, (.metadata.annotations["argocd.argoproj.io/tracking-id"] // "-")] | @tsv'
Deployment podinfo podinfo-dev:apps/Deployment:podinfo-dev/podinfo Service podinfo podinfo-dev:/Service:podinfo-dev/podinfo ConfigMap kube-root-ca.crt - HorizontalPodAutoscaler podinfo podinfo-dev:autoscaling/HorizontalPodAutoscaler:podinfo-dev/podinfo
2) Find resources in the cluster still tracked by label (left over from migration)
kubectl get deploy,sts,svc,cm -A -l argocd.argoproj.io/instance \ -o custom-columns=NS:.metadata.namespace,KIND:.kind,NAME:.metadata.name,APP:.metadata.labels.argocd\\.argoproj\\.io/instance
The upstream default key is app.kubernetes.io/instance; this lesson’s chart default key is argocd.argoproj.io/instance, adjust it to match your instanceLabelKey setting.
3) Before upgrading from v2, detect ApplyOutOfSyncOnly applications (official command)
kubectl get applications.argoproj.io -A -o json | jq -r '.items[] | select(.spec.syncPolicy.syncOptions[]? == "ApplyOutOfSyncOnly=true") | .metadata.name'
Lab: view the tracking-id, reproduce “mis-claiming” and “copying”
kubectl -n argocd get cm argocd-cm -o jsonpath='{.data.application\.resourceTrackingMethod}{"\n"}{.data.application\.instanceLabelKey}{"\n"}'
kubectl -n podinfo-dev get deploy podinfo -o jsonpath='{.metadata.annotations.argocd\.argoproj\.io/tracking-id}{"\n"}'
kubectl -n podinfo-dev get deploy podinfo --show-labels
annotation argocd.argoproj.io/instance podinfo-dev:apps/Deployment:podinfo-dev/podinfo NAME READY UP-TO-DATE AVAILABLE AGE LABELS podinfo 2/2 2 2 2d app.kubernetes.io/name=podinfo
copied, with the annotation pointing to Deployment podinfo:
kubectl -n podinfo-dev create configmap copied --from-literal=k=v kubectl -n podinfo-dev annotate configmap copied \ argocd.argoproj.io/tracking-id=podinfo-dev:apps/Deployment:podinfo-dev/podinfo sleep 10; argocd app get podinfo-dev --refresh | grep -E 'Sync Status|copied' kubectl -n podinfo-dev get cm copied
Sync Status: Synced to main (5d1a7c2) NAME DATA AGE copied 1 20s
The application stays Synced,copied and it is not pruned (in the UI it may appear at the top level, with no sync status).
claimed, with the annotation pointing to itself:
kubectl -n podinfo-dev create configmap claimed --from-literal=k=v kubectl -n podinfo-dev annotate configmap claimed \ argocd.argoproj.io/tracking-id=podinfo-dev:/ConfigMap:podinfo-dev/claimed sleep 15; kubectl -n podinfo-dev get cm claimed argocd app history podinfo-dev | tail -2 argocd app get podinfo-dev --show-operation | grep -i claimed
Error from server (NotFound): configmaps "claimed" not found
...
ConfigMap podinfo-dev claimed Pruned pruned
Argo CD thinks claimed belongs to podinfo-dev, but Git does not have it → extra resource → automated sync with prune enabled → deleted. In label mode, any object carrying the same instance label meets the same fate; this is one of the reasons v3 made annotation the default. If your application does not have automated prune enabled, it will show as OutOfSync and be marked requiresPruning.
application.resourceTrackingMethod to annotation+label,helm upgrade then argocd app sync podinfo-dev, then kubectl -n podinfo-dev get deploy podinfo --show-labels, you will see argocd.argoproj.io/instance=podinfo-dev. After verifying, change it back to annotation and upgrade and sync again.kubectl -n podinfo-dev delete cm copied --ignore-not-found; confirm argocd app get podinfo-dev is Synced/Healthy; the tracking method in values is annotation.Case 1: resources generated by an Operator are wrongly deleted
Problem: In the v2 era label tracking was used (default key app.kubernetes.io/instance), and an Operator also put the same instance label on the Secret it generated, with a value that happened to match an Argo CD application name. After enabling automated prune, the Secret was deleted every time it was generated, and the Operator kept rebuilding it. Approach: Upgrade to v3 and use annotation tracking; after upgrading, explicitly sync all applications once. Limitation: If the first sync after the upgrade includes deletions, the orphan edge case applies; rehearse in advance.
Case 2: two Argo CD instances manage the same cluster
Problem: The platform instance and the team instance both have an application named monitoring , and each treats the other’s resources as its own. Approach: Set a different installationID, and isolate them with AppProject destination namespaces (Hour 4). Limitation: After setting installationID, a sync is needed to write the new annotation.
Case 3: a migration tool requires selection by label
Problem: A cost-allocation and backup tool (such as Velero) selects application resources by the instance label; after migrating to annotation, the selector stops working. Approach: Use annotation+label: ownership is still determined by the annotation, and the label is only read by other tools. Limitation: Label values longer than 63 characters are truncated; take care on the tool side.
Common errors and fixes
SharedResourceWarning: ConfigMap/shared-config is part of applications argocd/app-a and app-b
Cause: Two applications both declare the same resource in Git, and the tracking metadata is rewritten back and forth.
kubectl -n NS get cm shared-config -o jsonpath='{.metadata.annotations.argocd\.argoproj\.io/tracking-id}'
Fix: A resource can have only one owner: remove it from one of the applications; use FailOnSharedResource=true to make such conflicts fail directly during sync.
A manually created resource is deleted for no apparent reason (the sync result shows pruned)
Cause: The resource carries a self-pointing tracking-id (copied or added manually), or in label mode carries a same-named instance label, and is treated as an extra resource of the application.
argocd app history APP argocd app get APP --show-operation | grep -i pruned
Fix: Remove the wrong tracking metadata; use annotation mode; add to critical resources Prune=false.
After upgrading to v3, resources deleted from Git were not pruned and remain in the cluster
Cause: An edge case recorded in the official docs: the first sync after switching tracking methods includes a deletion, and the old resource has a label but no annotation, so it cannot be recognized.
Fix: Manually delete these orphans; in future, run a sync for all applications before and after upgrades. You can use argocd app resources APP --orphaned (requires orphan monitoring to be enabled) to find them.
After switching tracking methods, resources still have only the old label / no annotation
Cause: New tracking metadata is only written during sync.
Fix: Run a sync on the application (applications with ApplyOutOfSyncOnly need a full sync).
1. Write out the tracking-id of Service podinfo in podinfo-dev.
podinfo-dev:/Service:podinfo-dev/podinfo
The core group is empty, so right after the colon comes /Service.
2. Use one command to count the number of Deployments each application owns in the cluster (annotation mode).
kubectl get deploy -A -o json | jq -r '.items[].metadata.annotations["argocd.argoproj.io/tracking-id"] // empty | split(":")[0]' | sort | uniq -cYou are responsible for upgrading Argo CD from v2.14 to v3.6 across 30 clusters. They currently use label tracking, and 5 applications have ApplyOutOfSyncOnly enabled. Write out the checks to perform before and after the upgrade.
Before upgrading: confirm resourceTrackingMethod is empty/label; list ApplyOutOfSyncOnly applications with the official jq command; freeze changes that involve deleting resources. After upgrading (read the upgrade notes version by version, 2.14→3.0→…): run one sync on all applications (for ApplyOutOfSyncOnly applications, untick the option in the UI or call the API to do a full sync); spot-check that resources show the tracking-id annotation; check for orphaned resources. If you need to postpone the migration, explicitly set label as a transition.
Verified teaching videos
No verified English video dedicated to “annotation vs label resource tracking” was found; refer to the official docs, upgrade notes and the storyboard script below.
Official docs
Video storyboard script (about 80 seconds)
These course materials cannot directly generate video/MP3; the storyboard and narration script are provided and can be handed to a video tool.
Visual: a Deployment with two name tags attached, one a label and one an annotation.
Narration: Argo CD recognizes its own resources through metadata on them. v3 uses the tracking-id annotation by default, and labels are also available.
Visual: a photocopier duplicates a Secret, and the label tag is copied too; in label mode, Argo CD’s hand reaches for the copy, and the copy is deleted.
Narration: labels are easily copied or written by other tools, so Argo CD treats other people’s resources as its own, and may even delete them when pruning is enabled.
Visual: the annotation content is magnified, showing app name, group, kind, namespace and name; the copy’s address does not match, so it is tagged “ignore”.
Narration: the annotation records the resource’s own address; once copied, the address no longer matches, so Argo CD ignores it.
Visual: upgrade checklist ticked: detect, sync all applications, handle ApplyOutOfSyncOnly.
Narration: when upgrading from v2 to v3, sync all applications once after the upgrade to avoid orphaned resources.
Module 8 · Sync control capstone lab
- Add a PreSync migration, a PostSync smoke test, a SyncFail alert and a dependency resource (Widget, wave -1, Lua health) to the myapp chart, and toggle them with environment values.
- Enable SSA and PruneLast on myapp-dev, and use the chart’s
autoscaling.enabledto avoid HPA replica-count drift at the root cause. - Complete one successful release and two failure drills (migration failure, dependency not ready), and use the troubleshooting decision tree to locate the problem within 2 minutes.
What: release blueprint
| Requirement | Mechanism | From module |
|---|---|---|
| Review the chart and environment configuration separately | Multi-source: apps/myapp + $values/values/myapp/dev.yaml | 1, 2 |
| Large objects, co-managed with HPA; diff must be accurate | ServerSideApply=true (v3.6 automatically uses Server-Side Diff) | 3 |
| Migrate first, dependency ready, then release, verify last | PreSync Job → wave -1 Widget → wave 0 workloads → PostSync smoke test; failure → SyncFail | 4 |
| Continue only when the dependency (Widget) is ready | Lua health check example.com_Widget | 5 |
| HPA manages replica count without drift | Root-cause fix: autoscaling.enabled: true the chart does not render replicas when replicas | 6 |
| Resource ownership is clear and auditable | annotation tracking; verify the tracking-id after release | 7 |
Why: why combine the drills
Each mechanism is easy to understand on its own; the real problems appear in combination: a PreSync hook cannot read configuration from the same application, PostSync never runs because some CR stays Progressing forever, ignoreDifferences hides real drift, and manual resources are wrongly pruned… The capstone lab lets you walk through these interactions within one application.
How: pre-release checklist
helm templateLocal rendering passes, and hook annotations and waves are correct (grep -E 'hook|sync-wave').argocd app diff myapp-dev --refresh’s diff matches expectations (only this change appears).- The dependency resource’s health check is in argocd-cm and has been tested with
argocd admin settings resource-overrides health. - Hooks are idempotent and have a timeout (
activeDeadlineSeconds), and there is nottlSecondsAfterFinished. - Release command:
argocd app sync myapp-dev && argocd app wait myapp-dev --health --timeout 600, and on failure collect--show-operationoutput.
When: when to use this whole set
Applications with stateful dependencies (databases, caches, external resource CRs) and externally facing services deserve the full set; purely stateless services with no dependencies need only SSA + health checks + a smoke test. The fewer hooks, the faster the sync and the less likely it is to get stuck.
Sequence diagram: one complete myapp-dev release
Failure map: where it is stuck, and where to look
Fault-injection simulator: myapp-dev release
Choose a fault (or “no fault”), play, and observe argocd app get myapp-dev --show-operation the stages, messages and resource states that would really appear, and get the next diagnostic command.
Release and diagnostic command list
| Stage | Command | What to look for |
|---|---|---|
| Before release | helm template myapp apps/myapp -f apps/myapp/values.yaml -f values/myapp/dev.yaml | grep -E 'kind:|hook|sync-wave' | Hooks and waves |
| Before release | argocd app diff myapp-dev --refresh | The diff contains only this change |
| Release | argocd app sync myapp-dev --async,argocd app wait myapp-dev --operation --health --timeout 600 | exit code |
| Stuck | argocd app get myapp-dev --show-operation | Phase, Message (waiting for …) |
| Hook | kubectl -n myapp-dev get jobs,kubectl -n myapp-dev logs job/myapp-db-migrate | Job status and logs |
| Health | argocd app get myapp-dev | grep -v Healthy | Unhealthy resources and messages |
| Terminate | argocd app terminate-op myapp-dev | Stop waiting (does not undo actions already performed) |
| After release | argocd app history myapp-dev,argocd app diff myapp-dev --exit-code | History; no residual drift |
# One-click release script (can be used directly in CI)
set -euo pipefail
APP=myapp-dev
argocd app diff "$APP" --refresh || true # diff returns non-zero when there are differences; shown here for display only
argocd app sync "$APP" --timeout 600 || {
echo "== sync failed, collecting details"; argocd app get "$APP" --show-operation
kubectl -n "$APP" get jobs; exit 1; }
argocd app wait "$APP" --health --timeout 600
Note: the namespace name happens to be the same as the application name (myapp-dev), so the script uses directly $APP as the namespace.
Lab: myapp-dev end-to-end release and failure drill
kubectl apply -f ~/gitops-lab/argocd/apps/widgets.yaml && argocd app sync widgets (you only need its CRD).
kubectl get crd widgets.example.com
kubectl -n argocd get cm argocd-cm -o jsonpath='{.data}' | jq -r 'keys[]' | grep Widget
argocd app get myapp-dev | head -12cd ~/gitops-lab
cat >> apps/myapp/values.yaml <<'EOF'
# ---- Argo CD Hour 2 capstone lab ----
hooks:
enabled: false
schemaVersion: "1"
failMigration: false
cache:
enabled: false
EOF
cat > apps/myapp/templates/argocd-hooks.yaml <<'EOF'
{{- if .Values.hooks.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "myapp.fullname" . }}-db-migrate
annotations:
argocd.argoproj.io/hook: PreSync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
backoffLimit: 0
activeDeadlineSeconds: 300
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: busybox:1.37
command:
- sh
- -c
- echo "migrating {{ .Release.Name }} to schema v{{ .Values.hooks.schemaVersion }}"; sleep 5{{ if .Values.hooks.failMigration }}; echo "ERROR lock timeout"; exit 1{{ end }}
---
apiVersion: batch/v1
kind: Job
metadata:
generateName: {{ include "myapp.fullname" . }}-smoke-
annotations:
argocd.argoproj.io/hook: PostSync
argocd.argoproj.io/hook-delete-policy: HookSucceeded
spec:
backoffLimit: 1
template:
spec:
restartPolicy: Never
containers:
- name: smoke
image: curlimages/curl:8.23.0
command: ["curl", "-fsS", "http://{{ include "myapp.fullname" . }}:{{ .Values.service.port }}/healthz"]
---
apiVersion: batch/v1
kind: Job
metadata:
generateName: {{ include "myapp.fullname" . }}-syncfail-
annotations:
argocd.argoproj.io/hook: SyncFail
argocd.argoproj.io/hook-delete-policy: HookSucceeded
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
containers:
- name: notify
image: busybox:1.37
command: ["sh", "-c", "echo 'ALERT: {{ .Release.Name }} sync failed in {{ .Release.Namespace }}'"]
{{- end }}
EOF
cat > apps/myapp/templates/widget.yaml <<'EOF'
{{- if .Values.cache.enabled }}
apiVersion: example.com/v1alpha1
kind: Widget
metadata:
name: {{ include "myapp.fullname" . }}-cache
annotations:
argocd.argoproj.io/sync-wave: "-1"
spec:
size: small
{{- end }}
EOF
Disabled by default (enabled: false), so myapp-prod is unaffected; only the dev values turn it on. {{ include "myapp.fullname" . }} With releaseName myapp, it renders as myapp.
cat > values/myapp/dev.yaml <<'EOF'
image:
tag: "6.17.0"
autoscaling:
enabled: true # the chart does not render Deployment.spec.replicas at this point; the HPA exclusively owns this field
minReplicas: 2
maxReplicas: 4
targetCPUUtilizationPercentage: 80
hooks:
enabled: true
schemaVersion: "2"
cache:
enabled: true
podAnnotations:
env: dev
resources:
requests:
cpu: 10m
memory: 32Mi
EOF
helm lint apps/myapp -f values/myapp/dev.yaml
helm template myapp apps/myapp -n myapp-dev -f apps/myapp/values.yaml -f values/myapp/dev.yaml \
| grep -E '^kind:|replicas:|argocd.argoproj.io|image:'
1 chart(s) linted, 0 chart(s) failed
kind: ServiceAccount
kind: Service
kind: Deployment
image: "ghcr.io/stefanprodan/podinfo:6.17.0"
kind: HorizontalPodAutoscaler
kind: Job
argocd.argoproj.io/hook: PreSync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
image: busybox:1.37
kind: Job
argocd.argoproj.io/hook: PostSync
...
kind: Widget
argocd.argoproj.io/sync-wave: "-1"
kind: Pod
image: busybox
The final kind: Pod is helm create built-in helm test Pod (helm.sh/hook: test), Argo CD does not support test hooks and ignores it. To remove it entirely, delete apps/myapp/templates/tests/. The output has no replicas:— once autoscaling is on, the Deployment no longer declares the replica count.
argocd/apps/myapp-dev.yaml ’s syncOptions, add ServerSideApply=true and PruneLast=true, then:
git add -A && git commit -m "myapp: hooks + widget dependency + HPA (dev)" && git push kubectl apply -n argocd -f argocd/apps/myapp-dev.yaml argocd app diff myapp-dev --refresh | head -40 argocd app sync myapp-dev --async sleep 20; argocd app get myapp-dev --show-operation | sed -n '1,12p'
Phase: Running Message: waiting for healthy state of example.com/Widget/myapp-cache
The PreSync migration has completed, the wave -1 Widget is judged Progressing by Lua, and the wave 0 workloads are waiting for it. This is exactly the “do not release while a dependency is not ready” behavior we want.
kubectl -n myapp-dev patch widget myapp-cache --subresource=status --type=merge \
-p '{"status":{"conditions":[{"type":"Ready","status":"True","message":"cache provisioned"}]}}'
argocd app wait myapp-dev --operation --health --timeout 300
argocd app get myapp-dev --show-operation | sed -n '/GROUP/,$p'
kubectl -n myapp-dev logs job/myapp-db-migrate
kubectl -n myapp-dev get deploy,hpa
kubectl -n myapp-dev get deploy myapp -o jsonpath='{.metadata.annotations.argocd\.argoproj\.io/tracking-id}{"\n"}'
GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE
batch Job myapp-dev myapp-db-migrate Succeeded PreSync ...
example.com Widget myapp-dev myapp-cache Synced Healthy ...
ServiceAccount myapp-dev myapp Synced ...
Service myapp-dev myapp Synced Healthy ...
apps Deployment myapp-dev myapp Synced Healthy ...
autoscaling HorizontalPodAutoscaler myapp-dev myapp Synced Healthy ...
batch Job myapp-dev myapp-smoke-… Succeeded PostSync ...
migrating myapp to schema v2
NAME READY UP-TO-DATE AVAILABLE
deployment.apps/myapp 2/2 2 2
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS
horizontalpodautoscaler.autoscaling/myapp Deployment/myapp cpu: 5%/80% 2 4 2
myapp-dev:apps/Deployment:myapp-dev/myapp
If TARGETS shows <unknown>, metrics-server is not ready (warm-up Step 4); the HPA’s health may therefore not be Healthy, and the PostSync smoke test will keep waiting. Install metrics-server, or temporarily turn off autoscaling in dev.
hooks.failMigration: true and push, then sync:
sed -i 's/^ schemaVersion: "2"/ schemaVersion: "3"\n failMigration: true/' values/myapp/dev.yaml git commit -am "dev: break migration" && git push argocd app sync myapp-dev; echo "exit=$?" argocd app get myapp-dev --show-operation | sed -n '1,8p' kubectl -n myapp-dev logs job/myapp-db-migrate
Phase: Failed Message: one or more synchronization tasks completed unsuccessfully ... migrating myapp to schema v3 ERROR lock timeout
PreSync fails → no workloads are updated (the Deployment is still the previous version) → SyncFail hook runs (it is deleted after success; you can use kubectl -n myapp-dev get events | grep syncfail to see that it existed). Fix: delete failMigration: true line, push, and sync again.
Ready=False, reason=Failed (see the Module 5 commands), then make any change to the dev values (such as podAnnotations.rev: "2"), and sync. Observe: Widget Degraded, application health Degraded; walk through the diagnosis with the decision tree on the “Troubleshooting” page below. To recover, set the Widget back to Ready=True.argocd app get myapp-dev | grep -E 'Sync Status|Health Status' argocd app diff myapp-dev --exit-code && echo "no drift" argocd app history myapp-dev | tail -4
Acceptance: Synced/Healthy, no residual drift, and both the failed and successful runs visible in history. Cleanup after class (keeping it until Hour 3 is also fine): argocd app delete myapp-dev myapp-prod widgets --yes and delete the corresponding namespace.
Case 1: release orchestration for a payment service
Problem: The payment service depends on a database schema and a cloud message queue created by Crossplane; in the past, “the new version started before the queue was ready” happened often. Approach: PreSync Flyway migration (credentials from ESO, separate application); the queue CR goes in wave -1 and uses a community Lua health check; apply wave 0; PostSync synthetic transaction smoke test; SyncFail sends to the on-call channel via Notifications (Hour 6). Limitation: The whole sync takes at most 15 minutes, so the CI wait timeout must be longer than that; migrations must be backward compatible so the old version can still run if one fails.
Case 2: speeding up sync for a large application
Problem: A monitoring application with 3000 objects takes 6 minutes per sync, and its status size is approaching the etcd limit. Approach:ApplyOutOfSyncOnly=true + SSA; split rules and dashboards into separate applications; remove unnecessary PostSync hooks. Limitation: If this application previously used label tracking, a full sync is needed after upgrading to v3 (Module 7).
Case 3: smoke test “false success”
Problem: The smoke test only accesses /healthz, while a new-version misconfiguration causes business APIs to return 500, yet the release shows success. Approach: The smoke test covers critical business paths (read-only endpoints) and checks the version (such as podinfo’s /version) and configuration markers, to avoid “an old Pod answering the request”. Limitation: A smoke test is not a full test; in production, combine it with Rollouts metric analysis to ramp up gradually.
Interactive troubleshooting decision tree: sync and health
Start from the symptom you see and choose step by step; finally you get the diagnostic command and a fix suggestion.
Supplement: the three most common errors
one or more synchronization tasks completed unsuccessfully
Cause: A task (resource apply or hook) failed. The message itself contains no details.
argocd app get myapp-dev --show-operation | awk 'NR==1 || /Failed|SyncFailed|Error/'
Fix: Handle it by the stage where the failed task sits (for hooks, check the Job logs; for resources, check the API error in the MESSAGE column).
waiting for healthy state of example.com/Widget/myapp-cache
Cause: A resource in the wave is not Healthy.
kubectl -n myapp-dev get widget myapp-cache -o jsonpath='{.status}'
Fix: Fix the controller or dependency; confirm the Lua logic is correct; if needed, terminate-op.
ComparisonError: Failed to load target state: ... $values/values/myapp/dev.yaml: no such file or directory
Cause: Wrong multi-source ref name or path (Module 2).
Fix: Check ref: values and the path; argocd app get myapp-dev --hard-refresh.
1. When a release is stuck, print the current operation stage and message with one command.
argocd app get myapp-dev -o json | jq -r '.status.operationState | "\(.phase): \(.message)"'
2. List the results of all hooks in myapp-dev’s most recent sync.
argocd app get myapp-dev -o json | jq -r '.status.operationState.syncResult.resources[] | select(.hookType != null) | "\(.hookType)\t\(.kind)/\(.name)\t\(.hookPhase)"'
During a release the PreSync migration succeeds, but the PostSync smoke test fails: the application is Synced but the operation is Failed. The database already has the new schema, and the workloads are already the new version. What would you do?
First check the smoke logs to confirm whether it is a real failure or a problem with the test itself. For a real failure: Git revert the application version (schema migrations should be backward compatible, so the old version can run on the new schema), sync, then smoke-test again; if the migration is not compatible, run the pre-prepared rollback script (do not rely on Argo CD automatic rollback). Afterwards: cover more critical paths in the smoke test; consider progressive delivery with Rollouts.
Verified teaching videos
Official docs
Video storyboard script (about 100 seconds)
These course materials cannot directly generate video/MP3; the storyboard and narration script are provided and can be handed to a video tool.
Visual: the myapp-dev release blueprint, with the chart and values sources flowing into repo-server.
Narration: the capstone lab puts this lesson’s seven mechanisms into one release.
Visual: the migration Job completes, the Widget card shows progressing, and the workload cards queue up; once the Widget turns green, the workloads start rolling.
Narration: the Lua health check on the dependency makes later waves wait; a new version is not released until the dependency is ready.
Visual: the migration Job turns red, a SyncFail alert pops up, and the Deployment stays on the old version.
Narration: when the migration fails, the sync stops in the PreSync phase, workloads are not updated, and SyncFail handles the alert.
Visual: the troubleshooting decision tree is clicked through from “sync stuck” all the way to “waiting for healthy state”.
Narration: first check the operation message to locate the stage, then check the corresponding object, and find the cause within two minutes.
Command cheat sheet: Application deep dive
1. Sources and rendering
argocd app manifests APP [--source live] argocd app get APP --show-params argocd app set APP --kustomize-image IMG:TAG argocd app set APP -p key=value # Helm parameter argocd app set APP --values values-prod.yaml argocd app unset APP -p key argocd app create APP --repo URL --helm-chart podinfo \ --revision 6.17.0 --dest-namespace NS --dest-server https://kubernetes.default.svc kubectl kustomize PATH ; helm template REL CHART -f VALUES
2. Multi-source
sources:
- repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
path: apps/myapp
helm:
valueFiles:
- $values/values/myapp/dev.yaml # always relative to the repo root
- repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
ref: values # no path: provides files only
# CLI: argocd app create APP --file app.yaml
# argocd app set APP --source-position 1 --revision TAG3. Sync options
syncPolicy: syncOptions: - CreateNamespace=true - ServerSideApply=true # v3.6 → Server-Side Diff - PruneLast=true - ApplyOutOfSyncOnly=true # large apps; hooks still run - RespectIgnoreDifferences=true - FailOnSharedResource=true - PrunePropagationPolicy=foreground # resource-level annotation (comma-separated): # argocd.argoproj.io/sync-options: Prune=false,Delete=false # argocd.argoproj.io/sync-options: Replace=true | Force=true,Replace=true
4. Waves and hooks
metadata:
annotations:
argocd.argoproj.io/sync-wave: "-1" # default 0, lower first
argocd.argoproj.io/hook: PreSync # Sync PostSync SyncFail Skip
# PreDelete(v3.3+) PostDelete
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
# HookSucceeded HookFailed
# order: phase → wave → kind → name; 2s between waves (ARGOCD_SYNC_WAVE_DELAY)
# selective sync (--resource) does not run hooks5. Sync and observe
argocd app sync APP [--dry-run] [--server-side] [--prune] argocd app sync APP --resource apps:Deployment:NAME argocd app sync APP --apply-out-of-sync-only argocd app wait APP --operation --health --timeout 600 argocd app get APP --show-operation argocd app terminate-op APP argocd app history APP argocd app logs APP --kind Job --group batch --name NAME
6. Health (Lua, Helm values)
configs:
cm:
resource.customizations.health.example.com_Widget: |
hs = {status = "Progressing", message = "waiting"}
if obj.status ~= nil and obj.status.conditions ~= nil then
for i, c in ipairs(obj.status.conditions) do
if c.type == "Ready" and c.status == "True" then
hs.status = "Healthy"; hs.message = c.message
end
end
end
return hs
# test: argocd admin settings resource-overrides health obj.yaml --argocd-cm-path cm.yaml
# ignore: argocd.argoproj.io/ignore-healthcheck: "true"7. Diff
spec:
ignoreDifferences:
- group: apps
kind: Deployment
jsonPointers: [/spec/replicas]
- group: apps
kind: Deployment
jqPathExpressions:
- .spec.template.spec.initContainers[] | select(.name == "x")
- group: "*"
kind: "*"
managedFieldsManagers: [kube-controller-manager]
# system-level: resource.customizations.ignoreDifferences.<group>_<kind> / .all
# argocd app diff APP --refresh --exit-code8. Resource tracking
kubectl -n argocd get cm argocd-cm -o jsonpath='{.data.application\.resourceTrackingMethod}'
kubectl get deploy NAME -n NS \
-o jsonpath='{.metadata.annotations.argocd\.argoproj\.io/tracking-id}'
# format: <app>:<group>/<kind>:<namespace>/<name>
# methods: annotation (default) | annotation+label | label
# chart default instanceLabelKey: argocd.argoproj.io/instance
# multiple instances: installationIDQuick troubleshooting table
| Symptom / error | Most likely cause | First command |
|---|---|---|
ComparisonError … kustomize build … failed | overlay/base path, version differences | kubectl kustomize PATH |
… $values/… no such file or directory | Wrong ref name or path | kubectl -n argocd get app APP -o yaml |
namespaces "X" not found | Missing CreateNamespace | argocd app get APP |
metadata.annotations: Too long | client-side apply annotation over the limit | Add ServerSideApply=true |
field is immutable | Changed an immutable field | resource-level Force=true,Replace=true (one-time) |
waiting for completion of hook … | Hook Job running / stuck | kubectl logs job/NAME |
waiting for healthy state of … | Resource in wave unhealthy / CR has no health check | argocd app get APP | grep -v Healthy |
| OutOfSync right after sync | Controller / webhook / HPA changes a field | argocd app diff APP + managedFields |
| Manual resource pruned | Self-referencing tracking-id / label conflict | argocd app history APP |
SharedResourceWarning | Two applications declare the same resource | Check the tracking-id |
Recommended configuration snippet: production Application template
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp-prod
namespace: argocd
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: default # change to team-a in Hour 4
sources:
- repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main # in production, pin a tag, e.g. myapp-0.2.0
path: apps/myapp
helm:
releaseName: myapp
valueFiles: [values.yaml, $values/values/myapp/prod.yaml]
- repoURL: https://github.com/<you>/gitops-lab.git
targetRevision: main
ref: values
destination:
server: https://kubernetes.default.svc
namespace: myapp-prod
syncPolicy:
automated:
enabled: true
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
- ServerSideApply=true
- PruneLast=true
- FailOnSharedResource=true
retry:
limit: 3
backoff: {duration: 10s, factor: 2, maxDuration: 2m}
Capstone lab + final quiz
Scenario
In Hour 1 an Application was created only for dev. Now the team needs to launch podinfo-prod (Kustomize prod overlay, 3 replicas, 6.16.0). Requirements: ① the namespace carries Pod Security labels; ② use SSA; ③ run a “change check” PreSync hook before release, run a smoke test after release, and have a SyncFail alert on failure; ④ the replica count is managed by the HPA (min 3, max 6) and does not drift; ⑤ PVCs (simulated data) in the production namespace are never pruned or deleted with the application; ⑥ after delivery, you can prove resource ownership and no drift.
apps/podinfo/overlays/prod/ add hpa.yaml (min 3, max 6), and remove the overlay’s replicas: block and add a JSON patch remove /spec/replicas (Module 6 Fix A). Locally, kubectl kustomize apps/podinfo/overlays/prod | grep -c 'replicas:' should be 0.# apps/podinfo/overlays/prod/data-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: podinfo-data
annotations:
argocd.argoproj.io/sync-options: Prune=false,Delete=false
argocd.argoproj.io/sync-wave: "-1"
spec:
accessModes: [ReadWriteOnce]
resources:
requests:
storage: 1Gi
kind’s default StorageClass is WaitForFirstConsumer, and a PVC stays Pending when no Pod uses it; its health is Progressing, which blocks waves! Choose one fix: have podinfo mount it (this affects multi-replica scheduling), or do not give it a wave and add argocd.argoproj.io/ignore-healthcheck: "true". Explain the reason for your choice.
change-check Job (busybox, prints Git version info, BeforeHookCreation), a PostSync smoke test (curl http://podinfo:9898/readyz, HookSucceeded), and a SyncFail alert (HookSucceeded). Refer to the Module 4 manifests; images busybox:1.37,curlimages/curl:8.23.0.argocd/apps/podinfo-prod.yaml: path apps/podinfo/overlays/prod,managedNamespaceMetadata (pod-security.kubernetes.io/enforce: baseline), syncOptions CreateNamespace,ServerSideApply,PruneLast,FailOnSharedResource; Do not enable automated sync yet (the first production release is manual).cd ~/gitops-lab && git add -A && git commit -m "podinfo-prod: production-grade application" && git push kubectl apply -n argocd -f argocd/apps/podinfo-prod.yaml argocd app diff podinfo-prod --refresh | head -60 argocd app sync podinfo-prod && argocd app wait podinfo-prod --health --timeout 600 argocd app get podinfo-prod --show-operation | sed -n '/GROUP/,$p'
/status/500 (podinfo returns 500) to trigger SyncFail, then restore; ② kubectl -n podinfo-prod scale deploy podinfo --replicas=5, confirm the application still shows Synced and the HPA takes over; ③ delete the PVC file from the overlay and sync, and confirm the PVC is still there and the application shows it needs pruning but was not deleted.kubectl get ns podinfo-prod --show-labels kubectl -n podinfo-prod get deploy,hpa,pvc,svc -o json | jq -r '.items[] | [.kind,.metadata.name,(.metadata.annotations["argocd.argoproj.io/tracking-id"] // "-")] | @tsv' argocd app diff podinfo-prod --exit-code && echo "no drift" argocd app history podinfo-prod
Delete=false keeps it), then argocd app delete podinfo-prod --yes.Open-ended self-test (answer first yourself, then expand the reference points)
1. When do you choose multi-source, when a Kustomize overlay, and when an ApplicationSet?
Multi-source: external chart + own values, or the chart and configuration belong to different teams. Kustomize overlay: environment differences in in-house manifests. ApplicationSet: you need to generate many Applications in bulk (multiple environments, multiple clusters). The three are often combined: an ApplicationSet generates a multi-source Application for each environment.
2. Explain the change ServerSideApply=true brings to “comparison” in v3.6, and its cost.
Automatically switches to Server-Side Diff: the API server predicts the result with an SSA dry-run, default values and webhook changes are included, false positives decrease, and validating webhooks report errors in the diff stage. The cost is extra API requests (cached), and newly created resources do not get Server-Side Diff. You can use compare-options: ServerSideDiff=false to revert.
3. Why should a PreSync migration hook not depend on a Secret in the same application?
PreSync runs before the Sync phase; on the first deployment the Secret does not exist, and after rotation it reads the old value. Credentials should come from outside the application, or the Secret itself should be a PreSync hook in a lower wave.
4. What problem does a team’s in-house CR without a health check cause for wave orchestration?
A resource with no health state does not block waves, so later waves start before the CR is ready; at the same time, application health cannot reflect its failure. Write and test a Lua health check for it.
5. List three ways to eliminate “permanent OutOfSync”, ordered by recommendation.
① Fix the root cause (remove fields managed by others from Git, write in the controller’s order, explicitly assign random values); ② enable SSA (Server-Side Diff); ③ precise ignoreDifferences (scoped by kind/name, minimal path), combined with RespectIgnoreDifferences where needed. System-level .all broad rules should be considered last.
6. What are the risk points when upgrading from v2.14 (label tracking) to v3?
If the first sync after switching includes deletions, orphans are created; ApplyOutOfSyncOnly applications need one full sync; external tools that depend on the instance label will break (annotation+label can help); tracking annotations only appear after sync. You should also read about other breaking changes, such as RBAC (logs, update/delete subresources) and status being ignored.
Sources and version notes
Sources table
| Topic | Verified finding | Source (accessed 2026-11-17) |
|---|---|---|
| Argo CD version | Latest stable v3.6.1 (2026-11-04); concurrently maintained v3.5.7, v3.4.13, v3.3.19 | GitHub Releases |
| Helm chart | argo-cd 10.18.0 (2026-11-11), appVersion v3.6.1; default configs.cm."application.instanceLabelKey": argocd.argoproj.io/instance, config defaults resource.customizations.ignoreResourceUpdates.all | argo-helm charts/argo-cd |
| Tool detection | Explicit configuration first; Chart.yaml → Helm; kustomization.yaml/.yml/Kustomization → Kustomize; otherwise directory | Tool Detection |
| Helm values precedence | parameters > valuesObject > values > valueFiles > chart values.yaml; Helm is only used for helm template | Helm |
| OCI | Helm OCI repository repoURL without oci://; native OCI source oci://, single-layer artifacts; the v3.1.0 release notes include “oci support (Beta)” | OCI,v3.1.0 release |
| Helm v4 | from v3.5, Helm 4.2.0 is built in; spec.source.helm.version are ignored; plain-HTTP OCI requires --insecure-oci-force-http | Upgrading 3.4 → 3.5 |
| Multi-source | sources — when present, the single-source setting is ignored source; $ref can only be at the start of a path and is relative to the repo root; a ref source cannot carry a chart; for same-name resources the later one takes effect with a RepeatedResourceWarning; the CLI uses --file | Multiple Sources |
| Sync options | SSA = apply --server-side --force-conflicts; Replace takes precedence over SSA; Force only takes effect with Replace or CSA; ApplyOutOfSyncOnly still runs hooks; CreateNamespace and managedNamespaceMetadata; Prune/Delete=confirm; default pruning is foreground | Sync Options |
| Server-Side Diff | Stable since v3.1.0; from v3.6 ServerSideApply=true automatically uses, Structured-Merge Diff has been removed | Diff Strategies,Upgrading 3.5 → 3.6 |
| Waves and hooks | Hook types include PreDelete (v3.3.0 release notes “PreDelete hooks support”) and PostDelete (v2.10+); default deletion policy BeforeHookCreation; default wave 0; wave delay 2s (ARGOCD_SYNC_WAVE_DELAY); ordering phase→wave→kind→name; selective sync does not run hooks; pruning is in reverse wave order; ttlSecondsAfterFinished is not recommended on hooks | Sync Phases and Waves,v3.3.0 release |
| Helm hook mapping | pre-install/pre-upgrade→PreSync, etc.; when Argo CD hooks are present, all Helm hooks are ignored | Helm Hooks |
| Health | Built-in assessment list; application health takes the worst (Healthy, Suspended, Progressing, Missing, Degraded, Unknown); Lua key format, wildcards, useOpenLibs; v3.6 deletionMessage; v3.4 Missing rule; v3.0 health no longer persisted to the CR | Resource Health,Upgrading 3.3 → 3.4 |
| Diff customization | jsonPointers / jqPathExpressions / managedFieldsManagers; system-level .all; v3 default ignoreResourceStatusField: all; jq timeout 1s; resource-annotation ignore-differences supports only jsonPointers; RespectIgnoreDifferences | Diffing Customization,Upgrading 2.14 → 3.0 |
| Resource tracking | Default annotation since v3.0; three methods; tracking-id format; non-self-referencing annotations are ignored; installationID; migration edge cases and ApplyOutOfSyncOnly handling; can use label exit | Resource Tracking,Upgrading 2.14 → 3.0 |
| CLI parameters | The app create/set/unset/sync/diff/manifests/get,admin settings resource-overrides health|ignore-differences parameters used in this lesson were checked against the v3.6.1 command reference | CLI Command Reference |
| Example images and chart | podinfo 6.17.0 (2026-10-26); Helm repository https://stefanprodan.github.io/podinfo, OCI oci://ghcr.io/stefanprodan/charts/podinfo; busybox 1.37 and curlimages/curl 8.23.0 tags exist on Docker Hub | podinfo, Docker Hub |
Video verification notes
All videos listed in this lesson were verified on 2026-11-17 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json), with titles and channel names confirmed to match: Akuity (MlAWr8bVr0I, Hn4pgrySYRU, aRKrDmqYLCE, eEqMEs2IY0I, bKroKvraCNE, xeFPB0NKmR0, ypkk48G71oo), Cloud With VarJosh (yyQgK1DeOkA, usj6RP6uzUc, SrgaMOuiqyY), DevOps & AI Toolkit (LKuRtOTvlXk, t1Fdse-F9Jw), DevOps Hobbies (XU08NQH11-Q), Prepare-sh (YTUCXc8BX3M), TheCodeAlchemist (EFjIM3TmhXQ), Amitabh Soni (pyEinvjEsys), I GET TO LIVE (sgSn7nmLSr0), Octopus Deploy (za_SNwjXehM). Details of community-channel videos follow this lesson and the official docs; no dedicated, verified videos were found for the two topics “Lua custom health checks” and “resource tracking methods”, so storyboard scripts are provided instead.
Audio narration notes
The “Audio” page uses the browser’s built-in Web Speech API to read the Chinese narration aloud (zh-CN), with English terms pronounced in en-US. These course materials cannot embed or generate MP3 files; the narration script can be used directly as a TTS script or recording script. Without a Chinese voice pack, install one as the page prompts, or just read the narration script.
Known limitations
- The command outputs in these course materials are all examples: these labs were written without running them against a real kind cluster and Argo CD; field names, column names and message wording come from the v3.6.1 official docs and command reference, but the exact formats (for example
--show-operationcolumns, failure messages, CLI exit codes) should be checked against your environment. - The only thing actually run and verified locally is the rendering of the myapp chart: in the scratchpad, using
helm create+ this lesson’s templates + dev valueshelm lintandhelm template(local helm 3.14; Argo CD v3.5+ has Helm v4 built in, which makes no difference for these simple templates). - The statement “PruneLast deletions are in the last implicit wave of the Sync phase, before PostSync” is based on the official docs’ description “as the last implicit wave of the sync” and on an understanding of the gitops-engine implementation; it is a conservative statement.
- HPA health assessment when metrics are unavailable may change between versions, so this lesson requires installing metrics-server first; the Widget lab has no real controller, so use
kubectl patch --subresource=statusto simulate it. - The native OCI source was introduced as Beta in v3.1; the v3.6 docs do not label its stage, so re-check its current status before production use. The v3.6 docs for multi-source Applications likewise carry no Beta label.
- The animations and simulators are simplified demonstrations of the real mechanisms (for example, the 2-second delay between waves is shortened and health assessment is completed instantly); they are not equivalent to the controller’s full implementation.