Hour 3: Multi-Application Management — App of Apps and ApplicationSet

From “hand-writing 3 Applications” to “one ApplicationSet generating all environments”: repo layout → bootstrap root app → generators → composite generators → preview environments → progressive syncs and promotion
Argo CD v3.6.1argo-cd chart 10.18.0ApplicationSet goTemplateProgressive Syncs: Beta (since v3.3), must be explicitly enabledVerified against official docs · 2026-11-17
Overall learning objectives
  • Use a tool-agnostic GitOps perspective to design a repo layout: monorepo or “app code repo + config repo”, with environments expressed via directories,branches or separate repositories, and explain why “one branch per environment” is not recommended; the same conclusion applies to Argo CD and Flux.
  • Understand the trade-off between DRY approaches (Kustomize overlays, Helm values-per-env) and the “rendered manifests pattern”, and know that Source Hydrator, Beta since Argo CD v3.5, is the official implementation of the latter.
  • Use App of Apps to write argocd/root.yaml, a single one that kubectl apply bootstraps the entire gitops-lab; know its permission risks, cascading deletion and Application health-check pitfalls.
  • Understand the ApplicationSet controller reconciliation loop: generators produce parameters → goTemplate render templates → templatePatch handle non-string fields → create / update / delete Applications per policy.
  • Be proficient with the List, Git directory / file and Cluster generators, as well as Matrix (Cartesian product) and Merge (key-based merge); be able to use the SCM Provider and Pull Request generator to automatically create preview environments for GitHub PRs, and configure tokens and safety switches correctly.
  • Enable RollingSync, so that dev → staging → prod sync group by group and wait for health; finally move podinfo-dev/staging/prod the three hand-written Applications to one ApplicationSet with zero downtime.

One-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (kind cluster lab)
0Before classPrep: multi-environment repo layoutCheck gitops-lab's overlays and add the staging / prod Application manifestsLayout self-assessmentThree overlays render successfully
100–06Repo layoutmonorepo vs app repo + config repo, environment directories vs branches vs separate repos, overlay / values-per-env, DRY vs rendered manifests, Flux comparison“Promoting a hotfix” comparison: branches vs directoriesCompare environment differences with diff
206–13App of Apps and bootstrappingroot app, directory recursion, cascading deletion, Application health checks, sync waves for staged bootstrapping, permission risksBootstrap timeline: root app → child Applications → workloadsWrite and apply argocd/root.yaml
313–21ApplicationSet: controller and templatescontroller reconciliation loop, goTemplate and missingkey=error, templatePatch, generator-level templates, sync policy and preserveResourcesOnDeletionParameters → template → Application renderer (editable parameters)List generator + argocd appset generate preview
421–28List, Git and Cluster generatorsList, Git directory (exclude), Git file (JSON/YAML flattening), Cluster (label selectors, local cluster), polling and WebhookGenerator expander: input → parameter sets → ApplicationGit directory generator scanning overlays
528–35Matrix and MergeCartesian product, parameter passing order, limits of the two child generators, Merge's mergeKeys and override orderCore animation: Git directory × cluster Matrix expansion + Merge overrideMatrix (overlay × cluster) preview
635–42SCM Provider and PR generatordiscovering repos by organization, generating preview environments per PR, token permissions, polling and Webhook, strict tokenRef mode, securityPR lifecycle: label → generate → push → close → deleteCreate a preview environment for a gitops-lab PR
742–50RollingSync and environment promotionProgressive Syncs status and switch, steps / maxUpdate, deletionOrder Reverse, promotion strategies (PR promotion, Kargo, Source Hydrator)RollingSync simulator (including stop on failure)Enable progressive syncs and watch group-by-group rollout
850–60Integrated labMigrate three hand-written Applications to one ApplicationSet with zero downtime; troubleshooting treeMigration step simulation + interactive troubleshooting treepodinfo ApplicationSet go-live
—After classCheat sheet · Integrated labPlatform building: root + appsets + preview environments + promotionFinal quiz (12 questions)Integrated lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / fieldsLab
Design a GitOps repo and environment layout (common to Argo CD / Flux)✓✓·✓··✓✓kubectl kustomize,diffenvironment diff
App of Apps bootstrapping and cascading deletion·✓·····✓directory.recurse, finalizerroot.yaml
ApplicationSet templates and goTemplate··✓✓✓✓✓✓goTemplate,templatePatchList preview
Basic generators (List / Git / Cluster)··✓✓✓··✓argocd appset generateGit directory
Composite generators (Matrix / Merge)····✓··✓matrix,mergeKeysoverlay × cluster
PR preview environments and SCM security·····✓··pullRequest.github,tokenRefpreview environments
Progressive syncs and environment promotion✓·····✓✓strategy.rollingSyncgroup-by-group rollout
Migration and troubleshooting (duplicates / conflicts / cascading deletion)·✓✓···✓✓argocd appset get, controller logsMigration drill

Content not covered in this lesson (and where to learn it)

TopicWhy it is not in this lessonWhere to learn it
Kustomize / Helm sources, multi-source Applications, sync waves details, health-check LuaManifests and sync control belonging to a single ApplicationHour 2
Second cluster lab2, AppProject, RBAC, SSO, apps / appsets in any namespaceThis lesson's Cluster generator only uses the local cluster and a “simulated” cluster Secret for demonstration; formal multi-cluster is covered in the next lessonHour 4
Argo Rollouts, Image Updater, Kargo hands-onThis lesson only covers the idea of “promotion” and RollingSyncHour 6
Full use of FluxThis lesson only covers Flux's equivalents in the repo layout and comparison tablesFlux: Ways of structuring your repositories
How CI changes Git (PRs that update image tags)Belongs to the CI topicGitHub 8 hours · GitLab 8 hours

How to use this course material

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · voice · video. Recommended: read “Principles” and “Animation” first, then do the “Lab”. The Matrix animation in Module 5 is the core of this lesson.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh if local storage is disabled).
Chinese voice
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the lecture script aloud; without a Chinese voice pack, the script can still be read or passed to a TTS tool.
Version notes This lesson is based on Argo CD v3.6.1 (released 2026-11-04, latest patch in the 3.6 series) and the official Helm chart argo-cd 10.18.0 as the baseline. The ApplicationSet controller is installed together with Argo CD, so no separate deployment is needed. Feature status was verified against the v3.6.1 docs: Progressive Syncs has been Beta since v3.3.0, but still must be explicitly enabled; deletionOrder: Reverse is available in the v3.6.1 docs; Source Hydrator has been Beta since v3.5.0, disabled by default; Matrix supports only two child generators, and composite generators can nest only one level. The podinfo image uses 6.16.0 and 6.17.0 (released 2026-10-26).

Module 0 · Prep: multi-environment repo layout (complete before class)

Confirm that gitops-lab has dev / staging / prod overlays, and prepare one Application manifest per environment — these are the objects this lesson will “upgrade”
Before class ≈ 10 minuteskind lab · Argo CD v3.6.1
Prerequisites
  • CompletedHour 1: kind cluster lab (context kind-lab), namespace argocd in which Argo CD was installed with Helm (release argocd, chart argo/argo-cd); locally you have ~/gitops-lab, with the remote being your GitHub repo gitops-lab (default branch main).
  • apps/podinfo/base (Deployment + Service, container name podinfod) and apps/podinfo/overlays/dev|staging|prod already exist; the overlay contains namespace: podinfo-<env>, replicas 1 / 2 / 3.
  • installed kubectl,helm,argocd CLI (ideally matching the server version),git, optional jq,yq.
  • Module 6 requires a GitHub personal access token (fine-grained, read-only); the other modules can be completed without it.

Step 1: Confirm the cluster, Argo CD and CLI login

kubectl config use-context kind-lab
kubectl -n argocd get deploy,sts
# Open another terminal to keep the port-forward running
kubectl -n argocd port-forward svc/argocd-server 8080:443
argocd login localhost:8080 --insecure --username admin
argocd version --short
argocd app list
NAME                                               READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/argocd-applicationset-controller   1/1     1            1           2d
deployment.apps/argocd-dex-server                  1/1     1            1           2d
deployment.apps/argocd-notifications-controller    1/1     1            1           2d
deployment.apps/argocd-redis                       1/1     1            1           2d
deployment.apps/argocd-repo-server                 1/1     1            1           2d
deployment.apps/argocd-server                      1/1     1            1           2d
NAME                                             READY   AGE
statefulset.apps/argocd-application-controller   1/1     2d
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  …

argocd-applicationset-controller Must be 1/1; half of this lesson's content depends on it. If the Helm values set applicationSet.replicas: 0, change it back to 1, then helm upgrade.

Step 2 (only if you have no results from the previous lesson): minimal starting point

If the cluster has been deleted, first followHour 1 “Environment setup”to rebuild the kind cluster, install Argo CD and create the gitops-lab skeleton (base + three overlays). Below are the minimal Argo CD install commands this lesson depends on:

kind create cluster --name lab
helm repo add argo https://argoproj.github.io/argo-helm && helm repo update
helm upgrade --install argocd argo/argo-cd --version 10.18.0 \
  -n argocd --create-namespace -f ~/gitops-lab/bootstrap/argocd-values.yaml
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath='{.data.password}' | base64 -d; echo

Step 3: Write one Application per environment (the “starting point” of this lesson)

In Hour 1 we only wrote argocd/apps/podinfo-dev.yaml. Now use it as a template to add staging and prod; the three files differ in only three places (name, path, namespace). This is exactly the duplication that Modules 3–8 remove with ApplicationSet. Note that the Hour 1 file carries resources-finalizer.argocd.argoproj.io (resources are cascade-deleted when the app is deleted), and the two copied files will carry it too. This is the “real trap” that must be handled first when migrating in Module 8.

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: podinfo-staging
  namespace: argocd
  finalizers:
  - resources-finalizer.argocd.argoproj.io
spec:
  project: default
  source:
    repoURL: https://github.com/<you>/gitops-lab.git
    targetRevision: main
    path: apps/podinfo/overlays/staging
  destination:
    server: https://kubernetes.default.svc
    namespace: podinfo-staging
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
    - CreateNamespace=true
    - PruneLast=true
cd ~/gitops-lab
for e in staging prod; do
  sed "s/podinfo-dev/podinfo-$e/g; s#overlays/dev#overlays/$e#" argocd/apps/podinfo-dev.yaml > argocd/apps/podinfo-$e.yaml
done
grep -nE 'name:|path:|namespace: podinfo|finalizer' argocd/apps/podinfo-*.yaml
for e in dev staging prod; do kubectl kustomize apps/podinfo/overlays/$e | grep -cE '^kind:'; done
git add argocd/apps && git commit -m "apps: podinfo staging/prod Applications" && git push
argocd/apps/podinfo-prod.yaml:4:  name: podinfo-prod
argocd/apps/podinfo-prod.yaml:7:  - resources-finalizer.argocd.argoproj.io
argocd/apps/podinfo-prod.yaml:14:    path: apps/podinfo/overlays/prod
argocd/apps/podinfo-prod.yaml:17:    namespace: podinfo-prod
…
2
2
2
[main 3f2a9c1] apps: podinfo staging/prod Applications
 2 files changed, 42 insertions(+)

If your podinfo-dev.yaml differs in structure from the one above (for example, it has no PruneLast), use your own file as the reference; sed only replaces the name, path and namespace. If the Hour 1 file does not exist, simply change the YAML above into the dev version and save it.

Note Here only commit, do not apply. The staging and prod Applications will be created automatically by the root app in Module 2 root . This is the point of App of Apps: the Applications in the cluster also come from Git. The already-existing podinfo-dev will be taken over by the root app, and the workloads will not be recreated.

Warm-up: answer from memory (30 seconds)

The Application's destination.namespace and the one in the overlay namespace: conflict: which one takes effect?

For a resource that explicitly sets a namespace in its manifest, the manifest wins; destination.namespace only applies to namespace-level resources without a namespace. So in this lesson the preview environment must use spec.source.kustomize.namespace to override the overlay's namespace (Modules 3, 6).

When you delete an Application, is the Deployment it manages deleted too?

It depends on whether the Application has resources-finalizer.argocd.argoproj.io: if it does, resources are cascade-deleted; if not, only the Application object is deleted (the resources become “orphans” and keep running). Modules 2 and 8 both rely on this.

Repo layout self-assessment (6 items)

Check the items your team has already achieved (results are saved in this browser). Come back and tick them again after finishing this lesson.

Environment self-check list

Module 1 · Repo layout: monorepo, multi-repo and environment directories

00:00 – 06:00 · Tool-agnostic GitOps patterns that apply to both Argo CD and Flux. The layout decides whether “promotion” is a clear file change or a risky branch merge
6 minTool-neutral (Argo CD / Flux)Source Hydrator: Beta (since v3.5)★★★★★
Learning objectives
  • Compare “monorepo” with “app code repo + config repo”, and choose based on team size, permission boundaries and CI feedback-loop risk.
  • Compare the three ways to express environments: directories (recommended),branches (not recommended),separate repositories (used for permission isolation); be able to name the 5 concrete problems of env-per-branch.
  • Understand the trade-off between the DRY approach of Kustomize overlays / Helm values-per-env and the “rendered manifests” pattern; know the Flux counterparts of App of Apps / ApplicationSet.
Prerequisites: Kustomize base/overlay (Hour 1), Helm values (Helm lesson). Importance:★★★★★ (once the layout is settled, migration is very costly)

What: the three questions a GitOps repo must answer

  1. Where do code and configuration live?— the same repository, or an application source repo plus a deployment config repo (config repo / environment repo).
  2. How are environments expressed?— directories under one branch (overlays/dev|staging|prod), one branch per environment, or one repository per environment.
  3. In what form is the desired state stored?— DRY templates (Kustomize overlays, Helm values) are rendered on the cluster side by the GitOps tool; or the rendered plain YAML is committed to Git (rendered manifests pattern).

These three questions have nothing to do with whether you use Argo CD or Flux: both pull the desired state from Git (or OCI) and continuously reconcile it. The only difference is “who describes which directories to deploy” (Argo CD's Application / ApplicationSet, Flux's Kustomization / HelmRelease).

Why: why “app code repo + config repo” is recommended

Argo CD's official Best Practices explicitly recommend keeping Kubernetes manifests in a repository separate from the application source code, for five reasons: ① changing only the replica count does not have to trigger a full CI build; ② the audit log is clean and contains only configuration changes; ③ one application may be built from several source repos but deployed as a whole; ④ permission separation: whoever can change the code may not be able to change production; ⑤ if CI commits image tags back to the same repository, it triggers a new CI run and forms an endless loop. Flux's official repository-structure guide gives the same options: Monorepo, Repo per team, Repo per app.

Monorepo (code + config)App code repo + config repo (recommended)Platform repo + one config repo per team
Suitable forpersonal projects, small teams, demosmost teamsmulti-team platforms (multi-tenancy in Hour 4)
CI writes image tags backeasily triggers a loop; needs path filters / [skip ci]write back to the config repo, no loopsame as left
Permissionscoarse: being able to merge code ≈ being able to change productionset CODEOWNERS and branch protection on the config repo separatelythe platform team controls root / appsets; teams change only their own directories or repos
gitops-lab in this lessonis a config repo: apps/ holds workload manifests,argocd/ holds Argo CD's own objects,bootstrap/ holds bootstrap files; podinfo's source code is upstream and not here.

How: directories, branches or separate repos for environments

ApproachExampleWhat is the promotion operation (dev → prod)Assessment
Environment directories (recommended)main under the branch overlays/dev,overlays/prodIn a PR, change the newTag of the prod overlay to the value verified in devAll environments are visible on one screen,diff -r so they can be compared; changes are fine-grained; the GitOps tool tracks only one branch
Environment branches (not recommended)dev,staging,prod three long-lived branchesmerge the dev branch into the prod branchsee the 5 problems below
Environment reposgitops-prod separate repositoriescross-repo commits / PRsused for strong permission isolation and compliance requirements; the cost is duplication and cross-repo syncing

Why “one branch per environment” is not recommended

  1. the merge carries “everything”: unverified changes and debug replica counts on the dev branch come along; when merging into prod you cannot pick only the image version. You can only cherry-pick, and over time the branch histories diverge.
  2. environment-specific differences and merge conflicts: each branch must keep its own replica count, domain name and resource limits. These “should never be merged” differences must be avoided by hand at every merge, and resolving the conflicts is itself a source of incidents.
  3. no global view: to find out “how prod differs from staging”, you need to git diff staging..prod, and the results are mixed with historical divergence; the directory approach needs only diff -r overlays/staging overlays/prod.
  4. the number of branches explodes with environments: environments × regions × clusters quickly become dozens of long-lived branches, and branch protection rules, Webhooks and CI must all be configured many times over.
  5. duplication with Helm / Kustomize: these tools were designed precisely for “one shared base + per-environment differences”; expressing environments again with branches is duplicate modeling.

Short-lived branches (feature branches, PR branches) are perfectly fine; the Module 6 preview environments are generated from PR branches. What is opposed is long-lived branches that represent environments. The most frequently cited argument in the community is Codefresh's “Stop Using Branches for Deploying to Different GitOps Environments”.

DRY or “rendered manifests”

DRY (overlays / values-per-env)Rendered manifests (rendered manifests pattern)
Stored in Git:base + a few per-environment differences (kustomization.yaml,values-prod.yaml)CI or a controller renders the templates into plain YAML and commits it to the environment directory / branch
Proschange one place and it affects all environments; fewer filesthe PR shows “what will actually be applied”; not affected by differences in rendering tool versions; the clearest audit trail
Conswhen changing the base, it is hard to see the real impact on prod at a glance (you need to diff the rendered results)needs extra rendering steps and write permissions; the repo is large
Tool supportArgo CD and Flux both render Kustomize and Helm nativelyArgo CD Source Hydrator (Beta since v3.5, disabled by default; requires enabling commit-server and setting hydrator.enabled: "true"); Flux and Argo CD can also render through CI

A compromise is common: keep the repo DRY, but in CI run, for each environment, kubectl kustomize / helm template and attach the rendered-result diff to the PR comments so reviewers see the real changes (step 3 of this module's “lab”).

Flux comparison: same layout, different “application manifests”

RequirementArgo CDFlux (v2.10)
describe “which directory goes where”Application (source + destination)Kustomization (sourceRef + path) or HelmRelease
environment differencesKustomize overlay / Helm values-per-env (same)same; Flux also supports postBuild.substitute variable substitution
bootstrap and “applications of applications”App of Apps: the root Application points at a directory full of Applications (this lesson's argocd/root.yaml)Kustomization tree: flux bootstrap in clusters/<name>/flux-system write the components and a root Kustomization; the root Kustomization in turn applies the child Kustomizations under infrastructure/,apps/ pointing at
batch generation (by list / directory / cluster / PR)ApplicationSet + generator (core component)Flux core no direct equivalent; the closest is Flux Operator's (ControlPlane release, v0.62.x) ResourceSet + ResourceSetInputProvider (supports inputs such as GitHubPullRequest and GitLabMergeRequest)
ordering and dependenciesSync Waves (within one application), RollingSync (groups of applications inside an ApplicationSet)Kustomization's dependsOn
multi-clusterCentralized: one Argo CD manages multiple clusters (Hour 4)Usually each cluster runs its own Flux, pulling from the clusters/<name> same repo

When: how to choose

  • Default: config repo + main branch + environment directories + overlays. All changes go through PRs; CODEOWNERS on the prod directory designates the approvers.
  • Compliance requires that “developers cannot read the prod configuration”: put prod in a separate repository, and give the GitOps tool separate credentials for that repository.
  • If the team is unsure about the impact of base changes: first add a “render diff” comment in CI; at larger scale, consider Source Hydrator.
Common misconceptions① “Branches naturally suit expressing environments, because Git Flow has develop/main”: Git Flow describes the release process of code, not deployment configuration; “promotion” of deployment configuration should be an exact change of values. ② “A monorepo puts everything together, so it is unsafe”: a monorepo combined with CODEOWNERS and directory-level approvals can separate permissions just as well; the main issue is CI feedback loops. ③ “The more thorough the DRY, the better”: an over-abstracted base makes one change affect all environments, and promotion loses its meaning; the differences between prod and dev should be explicit and readable.

Architecture diagram: recommended gitops-lab layout and how the two GitOps tools read it

App source repostefanprodan/podinfoCI build → ghcr.io image PR updates the tag Config repo gitops-lab (tracks only main) apps/podinfo/base/deployment.yaml · service.yaml apps/podinfo/overlays/dev/ 1 replica · 6.17.0staging/ 2 replicas · 6.16.0 prod/ 3 replicas · 6.16.0 argocd/root.yaml (App of Apps)argocd/apps/ → Applicationargocd/appsets/ → ApplicationSetargocd/projects/ → AppProject (Hour 4) bootstrap/argocd-values.yaml (Helm values) Argo CDApplication / ApplicationSetrepo-server renders the overlaycentrally manage multiple clusters Flux (comparison)GitRepository + Kustomizationkustomize-controller rendersusually one per cluster
Figure 1-1: the same config repo layout can be read by Argo CD or Flux; the only difference is “which object describes the deployment”

Comparison diagram: promoting one image version: what changes in the branch model vs the directory model

Environment branches (not recommended) dev prod tag 6.17debug=onreplicas 1new CM merge dev→prod: debug, replicas and the unverified CM all enter prod or cherry-pick → branches gradually diverge and conflicts keep recurring Environment directories (recommended) overlays/devnewTag: 6.17.0replicas: 1debug: on overlays/prodnewTag: 6.16.0 → 6.17.0replicas: 3 (unchanged)debug: off (unchanged) One PR, one line of diff: only the verified value is promoted diff -r overlays/staging overlays/prod shows the global differences at any time
Figure 1-2: promotion should be “an exact copy of a value”, not “a whole-branch merge”

Interactive comparison: how a prod hotfix flows through the two layouts

Scenario: prod has a defect, and the image must be hot-fixed from 6.16.0 to 6.17.0; meanwhile dev still has an unfinished debug switch. Click “Next”: both sides advance in sync, and you can observe the real Git operations at each step.

Environment-branch model
Environment-directory model
Ready. Both sides start from the same state: dev = 6.17.0 + debug switch, staging / prod = 6.16.0.
$ git log --oneline --all

Core commands: compare environments, review promotion

CommandPurposeNotes
diff -ru overlays/staging overlays/prodCompare the “source of differences” between two environmentsIn the directory model, the next command shows all differences
diff <(kubectl kustomize A) <(kubectl kustomize B)Compare rendered resultsMandatory when changing base; may differ from Argo CD's rendering due to kustomize version differences
git log --oneline -- apps/podinfo/overlays/prodChange history of prodAudit “who changed prod, and when”
argocd app diff podinfo-prod --local …Compare local files with the clusterPreview the impact before committing (login required)
flux bootstrap github …Flux comparison: initialize the Kustomization treeFor reference only; not run in this lesson
cd ~/gitops-lab
diff -ru apps/podinfo/overlays/staging apps/podinfo/overlays/prod
diff <(kubectl kustomize apps/podinfo/overlays/staging) <(kubectl kustomize apps/podinfo/overlays/prod)
-namespace: podinfo-staging
+namespace: podinfo-prod
…
-  count: 2
+  count: 3
…
-      value: "hello from staging"
+      value: "hello from prod"
+    - op: replace
+      path: /spec/template/spec/containers/0/resources/limits/memory
+      value: 256Mi

How to verify: staging and prod should differ only in fields that are “deliberately different” (namespace, replicas, message, memory limit). A difference in image tags means a promotion has not been completed. Common mistakes: Comparing only the overlay files and ignoring base changes. A base change affects all environments at once, so you must compare the rendered results. Production use: Make the rendered diff part of the PR checks.

Flux comparison (read-only reference)

# Flux bootstrap: write the flux-system components and a root Kustomization under the clusters/lab repo path
flux bootstrap github --owner=<you> --repository=gitops-lab --branch=main --path=clusters/lab --personal
# Afterwards, place Kustomizations under clusters/lab/ that point to apps/podinfo/overlays/* — this plays the same role as Argo CD's App of Apps

Lab 1: complete a “promotion review” with the directory model (about 5 minutes)

Check the current image version in each environment
cd ~/gitops-lab && git pull
grep -H newTag apps/podinfo/overlays/*/kustomization.yaml
apps/podinfo/overlays/dev/kustomization.yaml:  newTag: "6.17.0"
apps/podinfo/overlays/prod/kustomization.yaml:  newTag: "6.16.0"
apps/podinfo/overlays/staging/kustomization.yaml:  newTag: "6.16.0"

If dev is still 6.16.0, the Hour 1 Module 6 upgrade was not done. It does not affect this lab; just read “6.17.0” as “the version verified on dev”.

Promote staging from a short-lived branch (short-lived PR branches are fine; what is opposed is long-lived environment branches)
git switch -c promote-staging-6.17.0
sed -i 's/newTag: "6.16.0"/newTag: "6.17.0"/' apps/podinfo/overlays/staging/kustomization.yaml
git diff --stat
git diff
 apps/podinfo/overlays/staging/kustomization.yaml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
-  newTag: "6.16.0"
+  newTag: "6.17.0"

BSD sed on macOS must be written as sed -i '' 's/…/…/' file.

Generate the “rendered diff”: this is what the PR reviewer should see
R=$(mktemp -d)
git show main:apps/podinfo/overlays/staging/kustomization.yaml >/dev/null   # confirm that it exists on main
git stash -q && kubectl kustomize apps/podinfo/overlays/staging > $R/before.yaml
git stash pop -q && kubectl kustomize apps/podinfo/overlays/staging > $R/after.yaml
diff -u $R/before.yaml $R/after.yaml
-        image: ghcr.io/stefanprodan/podinfo:6.16.0
+        image: ghcr.io/stefanprodan/podinfo:6.17.0
Merge into main (a real team should open a PR on GitHub and get it approved; this lab can merge directly)
git commit -am "promote podinfo staging to 6.17.0"
git switch main && git merge --ff-only promote-staging-6.17.0 && git push
git branch -d promote-staging-6.17.0

At this point there is no podinfo-staging Application in the cluster yet (the root app creates them in Module 2), so no deployment happens for now. This is deliberate: Git comes first, then the cluster.

Think about it: if gitops-lab used three long-lived branches for dev / staging / prod, what would steps 2–4 become? Which step is the most error-prone? (Refer to the left column of the “Animation” page.)

Case 1: environment branches cause prod to inherit debug configuration

Problem: The team uses dev,prod two long-lived branches and merges dev → prod on every release. One release carried over a LOG_LEVEL=debug that had been temporarily turned on for troubleshooting in dev, and log volume jumped 20×. Approach: Migrate to main + overlays/, with environment-specific values kept in each overlay; promotion only changes the image tag. Configuration: CODEOWNERS designates the approvers for apps/*/overlays/prod/ . Limitations: During migration, the two layouts coexist, and applications must be switched one by one path and targetRevision.

Case 2: in a monorepo, CI writing image tags back triggers an endless build loop

Problem: Source code and manifests live in the same repository; CI builds and commits a new tag, and that commit triggers CI again. Approach: Split out a config repo, and let CI open PRs using a GitHub App that has write access only to the config repo. Limitations: After splitting, the mapping between “code version ↔ deployed version” must be maintained through image tags or commit messages.

Case 3: a base change unexpectedly affects prod

Problem: Someone changed the memory limit in base to 64Mi to “optimize dev”; after merging, prod was synced too and triggered OOMKilled. Approach: Run kubectl kustomize on each overlay in PR checks and comment the rendered diff; prod differences need confirmation from the prod approvers. Advanced: Evaluate Argo CD Source Hydrator (Beta), which commits the rendered results to Git before syncing.

Common errors and fixes

ComparisonError: … accumulating resources: … '../../base': no such file or directory

Cause: After moving directories, relative paths in the overlay break; or the Application's path points at the wrong level.

kubectl kustomize apps/podinfo/overlays/prod
argocd app get podinfo-prod -o json | jq -r '.spec.source.path'

Fix: Correct the resources: relative paths; layout changes must be done in the same PR as the path of the Application / ApplicationSet.

git merge dev → prod: CONFLICT (content): Merge conflict in overlays/kustomization.yaml

Cause: In the environment-branch model, both branches changed the same “environment-specific” field.

Fix: Short term: resolve the conflict by hand and check it line by line; long term: migrate to the environment-directory model, so environment-specific fields no longer take part in merges.

Two Applications manage the same resource: SharedResourceWarning

Cause: Two overlays (or the paths of two Applications) render resources with the same name and namespace, for example because the overlay was copied and the namespace was not changed.

argocd app get podinfo-staging | grep -i warning
kubectl -n podinfo-staging get deploy podinfo -o jsonpath='{.metadata.annotations.argocd\.argoproj\.io/tracking-id}'

Fix: Each environment's resources must have a unique namespace or name; the tracking ID shows which Application currently “wins”.

CI: refusing to allow a GitHub App to create or update workflow … / CI infinite loop triggered

Cause: In a monorepo, a CI write-back commit triggers CI again.

Fix: Split out the config repo, or exclude the manifest directory in the workflow with paths-ignore ; write-back commits use a token that does not trigger workflows.

Command-line tasks
1. Compare the rendered manifests of staging and prod with a single command.
diff <(kubectl kustomize apps/podinfo/overlays/staging) <(kubectl kustomize apps/podinfo/overlays/prod)
2. List the commits and authors that modified the prod overlay in the past 30 days.
git log --since=30.days --format='%h %an %s' -- apps/podinfo/overlays/prod
Scenario analysis
A new team proposes: “Use three branches for dev, staging and prod, with three Argo CD Applications each tracking one branch; then promotion is just a merge, which is intuitive.” How do you respond?

Point out 5 problems: the merge carries unverified changes; environment-specific differences cause repeated conflicts; environments cannot be compared on one screen; branches multiply with environments/regions; it duplicates the overlay modeling. Recommendation: the config repo uses only main, with environment directories overlays/<env> to express differences; promotion = a PR that changes the image tag in the prod overlay, with CODEOWNERS approval on the prod directory; short-lived PR branches can be used for preview environments (Module 6). The same conclusion applies to Flux.

Verified teaching videos

▶
GitOps: Branches, directories, or different repositories for the desired state of environments? — DevOps & AI Toolkit
English · exactly this module's question: branches, directories or separate repositories (tool-neutral)

Official docs and further reading

Video storyboard (about 90 seconds)

This course file cannot generate a video or MP3 directly; the storyboard and narration script are provided so they can be passed to a video tool.

Shot 1 · 0–20s
Visual: source repo on the left, config repo on the right, with a CI arrow pointing from left to right.
Narration: The first layout recommendation for GitOps: put deployment configuration in a separate config repo, and let CI only commit the new version number.
Shot 2 · 20–50s
Visual: dev and prod long-lived branches; a merge arrow carries a red “debug switch” into prod.
Narration: Expressing environments with branches turns promotion into a merge, and unverified changes are carried along with it.
Shot 3 · 50–75s
Visual: the overlays directory under the main branch, with only the newTag line for prod highlighted in green.
Narration: Expressing environments with directories makes promotion a single precise change, and all environments are visible on one screen.
Shot 4 · 75–90s
Visual: the same repository connected to both the Argo CD and Flux icons.
Narration: These layouts apply equally to Argo CD and Flux; the only difference is whether deployments are described with Application or Kustomization.
or reach a score of ≥ 70% in the “Quiz”

Module 2 · App of Apps pattern and bootstrapping

06:00 – 13:00 · One root Application points to a “directory full of Applications”; a single kubectl apply makes the whole repo take effect in the cluster
7 minargocd/root.yamlAdministrators only: can create applications in any project★★★★☆
Learning objectives
  • Write argocd/root.yaml: directory recursion, excluding itself, automatic sync; understand that “the Applications in the cluster also come from Git”.
  • Be able to explain the deletion semantics of root and child Applications (resources-finalizer.argocd.argoproj.io), so that one accidental deletion does not take an entire environment with it.
  • Know that since v1.8 Applications no longer have built-in health checks; to make sync waves “wait for health” between child apps, you need, in argocd-cm , to add a Lua health check.
Prerequisites: Application structure, automatic sync and prune (Hour 1), Sync Waves (Hour 2). Importance:★★★★☆

What: what App of Apps is

An Application is itself a Kubernetes custom resource (argoproj.io/v1alpha1, Kind=Application). Since Argo CD can sync Deployments from Git to the cluster, it can equally sync Application manifests from Git to argocd namespace. Root application (root / parent) whose source points to argocd/ a directory; the rendered result consists entirely of Application, ApplicationSet and AppProject objects. Once these child objects are created, the Application Controller reconciles each of them to its workloads. The official docs call this one way of “Cluster Bootstrapping”, recommend ApplicationSet as the first choice, and list App of Apps as an alternative.

Why: what problem it solves

  • Bootstrapping: after a new cluster has Argo CD installed, you only need kubectl apply -f argocd/root.yaml, and all the other applications appear automatically — especially important for disaster recovery.
  • Applications are versioned: adding an app = commit one file to argocd/apps/ ; deleting an app = delete the file (together with prune). There are no applications that exist “only in the UI”.
  • Managed in one place: the root app groups several applications for display, so they can be refreshed and their status checked together.

How: this lesson's root app

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: root
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/<you>/gitops-lab.git
    targetRevision: main
    path: argocd
    directory:
      recurse: true          # scan the apps/, appsets/ and projects/ subdirectories
      exclude: 'root.yaml'   # do not let the root app manage itself
  destination:
    server: https://kubernetes.default.svc
    namespace: argocd        # child Applications must be created in the argocd namespace (apps-in-any-namespace: see Hour 4)
  syncPolicy:
    automated:
      prune: true            # deleting a file under argocd/apps → deletes the corresponding Application
      selfHeal: true         # if someone edits a child app in the UI → revert it to what Git says
Key pointNotes
Directory-type sourceargocd/ has no kustomization.yaml, so Argo CD treats it as a “plain YAML directory”; recurse defaults to false and must be enabled to read subdirectories. A Helm chart can also generate child applications (official example argocd-example-apps/apps), which makes it easy to parameterize things like cluster addresses through values.
Root app has no finalizerDeleting the root app removes only itself; child Applications keep existing (becoming orphans). This is the safe default.
Finalizer on child appsIf a child Application carries resources-finalizer.argocd.argoproj.io, deleting it cascades to its workloads. If the root app prunes a child app file → the child Application is deleted → if it has a finalizer, its workloads are deleted too.
Health statusArgo CD 1.8 removed the built-in health assessment for Application resources, so the root app always shows child apps as “Healthy / no health”, even when a child is Degraded. When staged bootstrapping is needed, in argocd-cm , restore resource.customizations.health.argoproj.io_Application (see the Commands tab).
Staged bootstrappingAdd argocd.argoproj.io/sync-wave to child apps: for example, projects at -1, infrastructure at 0, business apps at 1. Only after the health checks above are restored will a later wave wait for the previous wave to become Healthy.

When: App of Apps or ApplicationSet

App of AppsApplicationSet (Modules 3–8)
Source of child appsHand-written Application filesGenerated automatically by generators + templates
Suitable fora small number of platform components with very different shapes (cert-manager, ingress, monitoring)many applications of the same shape (N environments × M clusters × K services, one per PR)
Readabilityeach application is clear at a glanceyou must understand the generators to know what will be generated (argocd appset generate preview)
Common combinationthe root app manages argocd/appsets/ the ApplicationSet inside “App of AppSets”. This lesson's root.yaml manages apps/, appsets/ and projects/ at the same time.
Security: App of Apps is an administrator tool The official docs warn: being able to create an Application in any Project is an administrator-level capability. Whoever can push to the root app's source repo can write an project: default, targeting the argocd namespace, and thereby modify Argo CD's own RBAC. Grant push permission only to administrators, and pay special attention in PR review to the project field of child apps (tightened with AppProject in Hour 4).
Common misconceptions① “Deleting the root app deletes all environments”: the root app has no finalizer by default and removes only itself; the truly dangerous case is a child app that has a finalizer and gets pruned. ② “The root app shows Healthy, so all child apps are healthy”: Application resources have no health check by default. ③ “A child app being OutOfSync makes the root app OutOfSync”: the root app compares the Application objects's spec, and does not care about the sync status of the child apps.

Structure diagram: root app → child Applications → workloads

Git: gitops-lab/argocd root.yaml (excluded)apps/podinfo-dev.yamlapps/podinfo-staging.yamlapps/podinfo-prod.yamlappsets/ · projects/ kubectl apply -fargocd/root.yaml (the only manual step) Application rootpath: argocd · recursedest ns: argocdauto · prune · selfHeal podinfo-devApplication podinfo-stagingApplication podinfo-prodApplication ns podinfo-devDeploy + Svc ns podinfo-stagingDeploy + Svc ns podinfo-prodDeploy + Svc
Figure 2-1: the root app only “deploys Application objects”; each child Application then reconciles its own workloads

Deletion semantics: whoever carries the finalizer cascades

Delete the root app (no finalizer)Only the Application root is deletedChild Applications and workloads keep runningSafe Prune a child app (no finalizer)The Application is deletedThe workloads become orphans and keep runningMust be cleaned up manually or re-adopted Prune a child app (with finalizer)Before the Application is deleted, first deleteall the resources it manages (cascade)Accidentally deleting a file = deleting an environment
Figure 2-2: the finalizer is the only switch for whether resources are taken away when an Application is deleted

Bootstrap timeline: what happens after a single kubectl apply

Tick “Restore Application health checks + sync waves” to compare the two bootstrap methods: by default all three child apps are created at the same time; with health checks restored, the root app waits for the previous wave's child apps to become Healthy before creating the next wave.

kubectl apply root— repo-serverRender argocd/ podinfo-dev— podinfo-staging— podinfo-prod— Workloads0 / 6 Pod Ready
Ready: the cluster has only Argo CD and the podinfo-dev from Hour 1.
$ kubectl apply -n argocd -f argocd/root.yaml

Core commands and parameters

CommandPurposeNotes
kubectl apply -n argocd -f argocd/root.yamlBootstrap the root appThe only manual step; you can also use the argocd-apps chart from argo-helm, or the extraObjects that installs the chart, to
argocd app get root --show-operationCheck which Applications the root app managesIn the resource list, Kind is Application
argocd app list -o nameList all applicationsv3 tracks resources with annotations by default, with no app.kubernetes.io/instance Filterable by label
argocd app delete APP --cascade=falseDelete only the Application, keep the resourcesUsed for migration and adoption
argocd app set root --directory-recurseEnable directory recursion from the command lineFor the declarative form, see root.yaml
kubectl apply -n argocd -f ~/gitops-lab/argocd/root.yaml
argocd app get root
argocd app list
Name:               argocd/root
Project:            default
Server:             https://kubernetes.default.svc
Namespace:          argocd
Source:
- Repo:             https://github.com/<you>/gitops-lab.git
  Target:           main
  Path:             argocd
Sync Policy:        Automated (Prune)
Sync Status:        Synced to main (3f2a9c1)
Health Status:      Healthy

GROUP        KIND         NAMESPACE  NAME             STATUS  HEALTH  HOOK  MESSAGE
argoproj.io  Application  argocd     podinfo-dev      Synced                application.argoproj.io/podinfo-dev configured
argoproj.io  Application  argocd     podinfo-prod     Synced                application.argoproj.io/podinfo-prod created
argoproj.io  Application  argocd     podinfo-staging  Synced                application.argoproj.io/podinfo-staging created

Note that the HEALTH column is empty. This is what “Application has no built-in health check” looks like.

Restore Application health checks (for staged bootstrapping with sync waves)

configs:
  cm:
    resource.customizations.health.argoproj.io_Application: |
      hs = {}
      hs.status = "Progressing"
      hs.message = ""
      if obj.status ~= nil then
        if obj.status.health ~= nil then
          hs.status = obj.status.health.status
          if obj.status.health.message ~= nil then
            hs.message = obj.status.health.message
          end
        end
      end
      return hs
helm upgrade argocd argo/argo-cd --version 10.18.0 -n argocd -f ~/gitops-lab/bootstrap/argocd-values.yaml
kubectl -n argocd get cm argocd-cm -o yaml | grep -A2 health.argoproj.io_Application

The Lua content comes from the official Resource Health docs. Once enabled, the root app's HEALTH column shows the real health of the child apps, and sync waves also wait for child apps to become Healthy.

Lab 2: bootstrap gitops-lab with root.yaml (about 6 minutes)

Write the root app and commit it (see the “Principles” page for the content; remember to replace <you>)
cd ~/gitops-lab
cat > argocd/root.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: root
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/<you>/gitops-lab.git
    targetRevision: main
    path: argocd
    directory:
      recurse: true
      exclude: 'root.yaml'
  destination:
    server: https://kubernetes.default.svc
    namespace: argocd
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
EOF
git add argocd/root.yaml && git commit -m "argocd: root app (App of Apps)" && git push
Bootstrap: the only manual apply
kubectl apply -n argocd -f argocd/root.yaml
sleep 20; argocd app list
NAME                    CLUSTER                         NAMESPACE        PROJECT  STATUS  HEALTH   SYNCPOLICY  …
argocd/podinfo-dev      https://kubernetes.default.svc  podinfo-dev      default  Synced  Healthy  Auto-Prune
argocd/podinfo-prod     https://kubernetes.default.svc  podinfo-prod     default  Synced  Healthy  Auto-Prune
argocd/podinfo-staging  https://kubernetes.default.svc  podinfo-staging  default  Synced  Healthy  Auto-Prune
argocd/root             https://kubernetes.default.svc  argocd           default  Synced  Healthy  Auto-Prune
Verify the workloads in the three environments
for e in dev staging prod; do kubectl -n podinfo-$e get deploy podinfo -o jsonpath='{.metadata.namespace} {.spec.replicas} {.spec.template.spec.containers[0].image}'; echo; done
podinfo-dev 1 ghcr.io/stefanprodan/podinfo:6.17.0
podinfo-staging 2 ghcr.io/stefanprodan/podinfo:6.17.0
podinfo-prod 3 ghcr.io/stefanprodan/podinfo:6.16.0
selfHeal also works for child apps: use a non-cascading delete method to remove one child Application and watch the root app recreate it. Note: podinfo-prod carries resources-finalizer, so running kubectl delete application directly would first delete all of prod's workloads!
argocd app delete podinfo-prod --cascade=false -y   # remove the finalizer first, then delete; resources are kept
kubectl -n podinfo-prod get deploy podinfo          # still running
sleep 15; argocd app get podinfo-prod | head -5     # already recreated by root (the finalizer came back from Git too)
(Optional) Try prune: deleting a child app file in Git makes the root app delete the corresponding Application. Do not try this on an application that has a finalizer. This step can be read-only: argocd app diff root will show the objects about to be deleted.
Cleanup The results of this lab (root + three child apps) are the foundation for later modules, so do not delete them. To start over completely: kubectl -n argocd delete application root (deletes only the root app), then delete the child Applications one by one argocd app delete podinfo-xxx.

Case 1: cluster disaster recovery completed in 15 minutes

Problem: A test cluster was accidentally deleted, and 40 platform components and business applications need to be rebuilt. Approach: New cluster helm install Argo CD → apply root.yaml; all applications recover automatically in wave order. Configuration: projects at wave -1, CRDs and operators at 0, business apps at 1; restore Application health checks so each later wave waits for the previous one. Limitations: Stateful data must be backed up separately (Velero, etc.); GitOps only restores the “declarations”.

Case 2: one accidental file deletion nearly deleted production

Problem: While restructuring directories, the path in git mv was written incorrectly, so the root app pruned the prod child app. That child app has a finalizer, so its workloads were cascade-deleted. Approach: Roll back the commit to restore; afterwards remove the finalizer from the prod child app (confirm manually when deleting the Application), and turn off automatic prune on the root app, switching to manual sync that reviews deletions. Limitations: Without a finalizer, deleting an application leaves orphan resources, which need periodic cleanup.

Case 3: a developer gained cluster admin through a child app

Problem: The root app's repo allowed all developers to push, and someone committed a project: default, targeting argocd namespace child Application that modified argocd-rbac-cm. Approach: Only the platform team may write to the root app repo, child apps use restricted AppProjects (Hour 4), and in CODEOWNERS, protect argocd/.

Common errors and fixes

Root sync succeeded but created 0 resources (the files under argocd/apps were ignored)

Cause: not enabled directory.recurse,argocd/ the top level contains only root.yaml, and it is excluded.

argocd app get root -o json | jq '.spec.source.directory'

Fix: Set recurse: true, or change path to argocd/apps.

application.argoproj.io "podinfo-dev" is invalid / InvalidSpecError: application destination … namespace podinfo-dev is not permitted

Cause: The AppProject used by the child app does not allow that destination (a common issue after tightening projects in Hour 4).

Fix: Check argocd proj get <project> destinations and sourceRepos.

The child Application was created in the podinfo-dev namespace, and Argo CD cannot see it

Cause: The child app YAML is missing metadata.namespace , while the root app's destination.namespace was set to the workload namespace. By default an Application can only be recognized in the argocd namespace.

Fix: Set the root app's destination.namespace to argocd, and explicitly write namespace: argocd in the child app.

Sync wave not working: wave 1 child apps start deploying while wave 0 is still Progressing

Cause: Application resources have no health check, so Argo CD considers a child app “healthy” as soon as it is created.

Fix: Add resource.customizations.health.argoproj.io_Application to argocd-cm (see the “Commands” page).

argocd app sync -l app.kubernetes.io/instance=root returns no apps match selector

Cause: The old docs relied on “label tracking”. Argo CD v3 uses annotation tracking by default (argocd.argoproj.io/tracking-id), so child Applications no longer carry that label.

Fix: Give the child apps their own label (for example gitops-lab/group: podinfo), then use -l gitops-lab/group=podinfo; or sync them one by one.

Command-line tasks
1. Delete only the Application podinfo-prod and keep its workloads.
argocd app delete podinfo-prod --cascade=false
# or: kubectl -n argocd delete application podinfo-prod (provided it has no resources-finalizer)
2. Find all Applications that carry the cascading-delete finalizer.
kubectl -n argocd get applications -o json | jq -r '.items[] | select(.metadata.finalizers // [] | map(startswith("resources-finalizer")) | any) | .metadata.name'
Scenario analysis
The platform team wants a new cluster to install cert-manager → ingress-nginx → monitoring → business applications automatically, with each step proceeding only after the previous one is healthy. How would you design this with App of Apps?

The root app points to argocd/ (recurse); give the four groups of child apps sync-wave 0/1/2/3; restore Application health checks in argocd-cm so the root app waits for child apps to be Healthy at each wave; platform component child apps use platform project; only the platform team may write to the root app repo. When there are many business apps of the same shape, put an ApplicationSet at wave 3 instead.

Verified teaching videos

▶
Argo CD Tutorial: App of Apps in 8 Minutes — Akuity
English · an 8-minute demo of the root app and child app structure, consistent with this module's lab

Official docs

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
Visual: an empty cluster with only Argo CD installed; the terminal runs kubectl apply root.yaml.
Narration: App of Apps needs only one manual step: create the root app.
Shot 2 · 20–45s
Visual: the root app node expands into three child app nodes, each of which then expands into a Deployment.
Narration: the root app deploys Application objects, and the child apps then sync their own workloads to the cluster.
Shot 3 · 45–75s
Visual: one child app file is deleted; a red finalizer icon flashes and the workloads disappear.
Narration: note the deletion semantics: when a child app with a finalizer is pruned, its resources are deleted along with it.
or reach a score of ≥ 70% in the “Quiz”

Module 3 · ApplicationSet: controller and templates

13:00 – 21:00 · Generators produce “parameter sets”; a template renders each parameter set into one Application; the controller creates, updates and deletes them and writes status back
8 mingoTemplate + missingkey=errortemplatePatch★★★★★
Learning objectives
  • Draw the reconciliation loop of the ApplicationSet controller: generate parameters → render template → apply templatePatch → create / update / delete Applications → write status conditions.
  • Always use goTemplate: true and goTemplateOptions: ["missingkey=error"]; be able to use Sprig,normalize,slugify; know that Go templates only act on string fields, while boolean / object fields must use templatePatch.
  • Master the Application modification policies (sync / create-only / create-update / create-delete),preserveResourcesOnDeletion,ignoreApplicationDifferences, and use argocd appset generate to preview before creating.
Prerequisites: Application fields (Hours 1–2), basic Go templates (same syntax as Helm templates). Importance:★★★★★

What: what an ApplicationSet is

ApplicationSet (argoproj.io/v1alpha1) is an “Application factory”: generators produces a set of parameter sets (each a key-value map),template is an Application template with placeholders; each parameter set renders one Application. It is reconciled by a separate component argocd-applicationset-controller , installed together with Argo CD (the applicationSet part of the Helm chart).

Why: what problem it solves

  • Removes duplication: podinfo-dev/staging/prod.yaml three files differ by only three values; 10 services × 3 environments × 2 clusters would mean 60 nearly identical files.
  • Automatic discovery: adding an overlay directory, registering a cluster or opening a PR makes the Application appear automatically; deleting it makes it disappear.
  • Unified changes: change the template once (for example, adding a syncOption) and it takes effect in all generated applications at once.

How: the controller's reconciliation loop

  1. Triggers: ApplicationSet changes, changes to the Applications it owns, cluster Secret changes, Git polling (default 3 minutes,requeueAfterSeconds adjustable per ApplicationSet), SCM/PR polling (default 30 minutes), or an ApplicationSet Webhook.
  2. Generate parameters: run each generator in spec.generators , and concatenate the results into a list of parameter sets (multiple top-level generators are combined as a “union”; combining them needs Matrix / Merge, Module 5). The Git generator reads the repo through repo-server.
  3. Render: render spec.template for each parameter set (if the generator itself has template, it is merged with the outer template first, with the generator's fields taking precedence); then the rendered templatePatch is applied as a patch.
  4. Validate: check that the name is valid and the target cluster and project exist; duplicate Applications with the same name raise an error.
  5. Apply: create or update Applications according to the policy, and set the ApplicationSet as their controller ownerReference —an existing Application with the same name is adopted (the Module 8 migration relies on exactly this); Applications that are no longer generated are deleted.
  6. Write status: status.conditions in ErrorOccurred,ParametersGenerated,ResourcesUpToDate,RolloutProgressing (progressive syncs, Module 7), and status.resources (up to 5000 entries by default since v3.2).

Template engines: fasttemplate vs Go template

Default (fasttemplate,{{name}})goTemplate: true ({{.name}}, recommended)
SyntaxSimple string substitution; nested parameters are written as {{path.basename}}Go text/template + Sprig (except env,expandenv,getHostByName) + normalize,slugify
Conditionals / loopsnot supportedsupported (but only inside a single string field)
Missing parameterskept as-isdefault output <no value>; with missingkey=error set, it errors out directly (strongly recommended)
templatePatchnot availableavailable
Statusthe official docs say it will be deprecatedNew ApplicationSets should always use

templatePatch: templating boolean and object fields

Go templates only act on string fields, so automated.prune: "{{.prune}}",syncPolicy: "{{.syncPolicy}}" both do not work. templatePatch is a block of that is rendered first and then merged as a patch into the template YAML/JSON; it can be used to if / range generate arbitrary structures: decide whether to enable auto-sync based on a parameter, or loop to generate several Helm valueFiles. Note three points (all from the official docs): it is only available when goTemplate: true is used; it does not support modifying spec.project; an empty spec: in the patch clears existing fields; when parameters come from untrusted input, use toJson to prevent injection.

Who can change Applications: modification policies and protected fields

SettingMeaning
--policy / applicationsetcontroller.policyController level: sync (default, does create, update and delete),create-only,create-update,create-delete
spec.syncPolicy.applicationsSyncthe policy of a single ApplicationSet; requires the controller to enable applicationsetcontroller.enable.policy.override, and the controller-level --policy takes precedence
spec.syncPolicy.preserveResourcesOnDeletion: trueApplicationSet deletion does not cascade-delete the Application's resources (recommended for production)
spec.ignoreApplicationDifferenceslets users manually change certain fields on the generated Application (such as temporarily disabling auto-sync) without them being reverted
spec.preservedFieldskeeps annotations / labels that other tools added to the Application

When: when to use ApplicationSet

When multiple Applications have the same shape and differ only in a few parameters, or need to be automatically added or removed based on external facts (directories, clusters, PRs). For a small number of platform components with different shapes, App of Apps is more intuitive. On permissions: an ApplicationSet can create applications in any project and can read Secrets in the argocd namespace as SCM tokens, so the official docs require that only administrators can create or modify ApplicationSets.

Common misconceptions① “Just edit the generated Application by hand”: the controller will revert it to the template's shape at the next reconciliation (unless configured to ignoreApplicationDifferences). ② “Deleting an ApplicationSet just deletes a template”: the Applications it owns are deleted too, and if an Application carries a finalizer, its workloads are deleted as well. ③ “Deploying ApplicationSet with Helm is fine”: Helm also parses {{ }}, which replaces {{.cluster}} with an empty string; it must be written as {{`{{.cluster}}`}}.

Architecture diagram: inputs and outputs of the ApplicationSet controller

ApplicationSet object Git (via repo-server) Cluster Secret (argocd ns) SCM / PR API (GitHub…) Webhook / polling timer argocd-applicationset-controller ① generators[]params ② templategoTemplate rendering ③ templatePatchboolean / object fields ④ Validatename / cluster / project ⑤ create / update / delete (per policy) + ownerReference⑥ status.conditions · status.resources · applicationStatus Application × Npodinfo-devpodinfo-stagingpodinfo-prod→ Application Controllersync as usual (Hour 1) The ApplicationSet controller only manages the Application objects themselves; syncing workloads is still done by the Application Controller
Figure 3-1: the two controllers divide the work: the ApplicationSet controller “writes Applications”, and the Application Controller “syncs Applications”

Template merge order

spec.templateOuter common template generator.templateSame-name field overrides the outer template (optional) Render {{.param}}Per string field + templatePatchMerge after rendering → Application
Figure 3-2: Matrix child generators do not process generator.template (one of the limits of Module 5)

Interactive renderer: parameter sets → template → Application

Edit the elements of the List generator below (a JSON array) and click “Render”. The animation highlights each step in the controller's real order; switch missingkey=error to observe the two outcomes when a parameter is missing (for example, by deleting the env key from an element).

generators[0].list.elements
template.metadata.name = podinfo-{{.env}} · path = apps/podinfo/overlays/{{.env}} · templatePatch: {{- if .autoSync}} add automated
controller steps
Click “Render”.
$ argocd appset generate podinfo.yaml

Core commands and parameters

CommandPurposeNotes
argocd appset generate FILERender the template on the server,without creating any objects-o yaml|json|wide; the first step when writing an ApplicationSet
argocd appset create FILE [--upsert] [--dry-run]Create / overwrite an ApplicationSetIn GitOps scenarios, usually commit it to argocd/appsets/ and let root sync it
argocd appset get NAMECheck conditions and generated appsFirst stop for troubleshooting
argocd appset list / deleteList / deleteDeleting also deletes the Applications it owns
kubectl -n argocd get applicationsetsSame as above (short name appsets)
kubectl -n argocd logs deploy/argocd-applicationset-controllerController logsRender errors, permission errors and SCM rate limiting all show up here
kubectl -n argocd annotate appset NAME argocd.argoproj.io/application-set-refresh=trueRefresh now (bypass the Git revision cache)The controller removes this annotation automatically after processing
argocd appset generate ~/appset-lab/podinfo-demo.yaml
argocd appset get podinfo-demo
NAME               PROJECT  SYNCPOLICY  …  REPO                                         PATH                       TARGET
argocd/demo-alpha  default  Auto-Prune  …  https://github.com/<you>/gitops-lab.git  apps/podinfo/overlays/dev  main
argocd/demo-beta   default  Manual      …  https://github.com/<you>/gitops-lab.git  apps/podinfo/overlays/dev  main

Name:               argocd/podinfo-demo
Project:            default
Server:             https://kubernetes.default.svc
Namespace:          demo-{{.name}}
…
CONDITION            STATUS  MESSAGE                                                    LAST TRANSITION
ErrorOccurred        False   All applications have been generated successfully   …
ParametersGenerated  True    All parameters have been generated successfully     …
ResourcesUpToDate    True    All applications have been generated successfully   …

How to verify:ResourcesUpToDate=True and ErrorOccurred=False. Common mistakes: When deploying an ApplicationSet via a Helm chart, you did not escape {{ }}. Production use: Put argocd appset generate into PR checks, with a comment on “which Applications this change adds / deletes”.

Controller parameters (argocd-cmd-params-cm; in Helm, written under configs.params)

configs:
  params:
    applicationsetcontroller.policy: sync                     # default; can be changed to create-only, etc.
    applicationsetcontroller.enable.policy.override: true     # allow a single ApplicationSet to set applicationsSync
    applicationsetcontroller.enable.tokenref.strict.mode: true  # Module 6: tokenRef may only reference the scm-creds Secret

Lab 3: first ApplicationSet (List generator + templatePatch, about 7 minutes)

This lab is run outside of the repo's ~/appset-lab/ directory. It uses kubectl to create objects directly and deletes them at the end, without affecting the root app. To avoid clashing with podinfo-dev, use kustomize.namespace to deploy the dev overlay to demo-alpha,demo-beta two new namespaces.

Write the ApplicationSet
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: podinfo-demo
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - list:
      elements:
      - name: alpha
        autoSync: true
      - name: beta
        autoSync: false
  template:
    metadata:
      name: 'demo-{{.name}}'
      labels:
        gitops-lab/group: demo
      finalizers:
      - resources-finalizer.argocd.argoproj.io   # for demo: clean up resources on deletion
    spec:
      project: default
      source:
        repoURL: https://github.com/<you>/gitops-lab.git
        targetRevision: main
        path: apps/podinfo/overlays/dev
        kustomize:
          namespace: 'demo-{{.name}}'          # overrides namespace: podinfo-dev in the overlay
      destination:
        server: https://kubernetes.default.svc
        namespace: 'demo-{{.name}}'
  templatePatch: |
    spec:
      syncPolicy:
        syncOptions:
        - CreateNamespace=true
    {{- if .autoSync }}
        automated:
          prune: true
          selfHeal: true
    {{- end }}

autoSync is a boolean and cannot be written in template string fields, so use templatePatch to generate automated blocks. Indentation matters: automated and syncOptions at the same level.

Preview first, then create
mkdir -p ~/appset-lab && cd ~/appset-lab    # save the YAML above as podinfo-demo.yaml and replace <you>
argocd appset generate podinfo-demo.yaml -o yaml | grep -E 'name: demo|automated|namespace: demo'
kubectl apply -f podinfo-demo.yaml
sleep 20; argocd app list -l gitops-lab/group=demo
    name: demo-alpha
      namespace: demo-alpha
      automated:
    name: demo-beta
      namespace: demo-beta
applicationset.argoproj.io/podinfo-demo created
NAME               CLUSTER                         NAMESPACE   PROJECT  STATUS     HEALTH   SYNCPOLICY
argocd/demo-alpha  https://kubernetes.default.svc  demo-alpha  default  Synced     Healthy  Auto-Prune
argocd/demo-beta   https://kubernetes.default.svc  demo-beta   default  OutOfSync  Missing  Manual

demo-beta has no automatic sync, so it shows OutOfSync / Missing — templatePatch is in effect.

Experience “the controller changes it back”: manually enable auto-sync on demo-beta, and it is reverted within seconds.
argocd app set demo-beta --sync-policy automated
sleep 10; argocd app get demo-beta | grep "Sync Policy"
Sync Policy:        Manual

If you want to allow such manual changes, add ignoreApplicationDifferences: [{jsonPointers: ["/spec/syncPolicy"]}] to the ApplicationSet.

Experience missingkey=error: change 'demo-{{.name}}' in the template to 'demo-{{.nam}}' and apply again:
sed -i "s/demo-{{.name}}'$/demo-{{.nam}}'/" podinfo-demo.yaml && kubectl apply -f podinfo-demo.yaml
sleep 5; argocd appset get podinfo-demo | grep -A1 ErrorOccurred
ErrorOccurred        True    failed to execute go template demo-{{.nam}}: template: :1:7: executing "" at <.nam>: map has no entry for key "nam"

When an error occurs, the controller does not delete existing applications; it only stops updating and reports conditions. Revert .name and apply again to recover.

Cleanup (delete the ApplicationSet → delete the two Applications → the finalizer cascades to delete the resources)
sed -i "s/demo-{{.nam}}'/demo-{{.name}}'/" podinfo-demo.yaml && kubectl apply -f podinfo-demo.yaml
kubectl -n argocd delete applicationset podinfo-demo
sleep 15; kubectl delete ns demo-alpha demo-beta --ignore-not-found

Case 1: one template change modified 300 applications at once

Problem: Someone changed targetRevision from main to HEAD, and 300 Applications refreshed at the same time, pegging repo-server CPU. Approach: Template changes go through a PR, and CI runs argocd appset generate to output a change summary; for large batches of applications, enable RollingSync (Module 7) to roll out group by group. Limitations: RollingSync turns off automatic sync for the generated applications.

Case 2: accidentally deleting an ApplicationSet emptied the environment

Problem: During a refactor, the old ApplicationSet was deleted; the generated applications carried finalizers, so all workloads were deleted. Approach: Always set syncPolicy.preserveResourcesOnDeletion: true on production ApplicationSets; the controller uses the create-update policy to prevent bulk deletion, and deletion becomes a manual operation. Limitations: The official docs warn that create-only / create-update does not by default stop “deleting applications when the ApplicationSet is deleted”; it must be used together with preserveResourcesOnDeletion.

Case 3: on-call staff need to temporarily pause auto-sync for an application

Approach: Configure ignoreApplicationDifferences to ignore /spec/syncPolicy, so that on-call staff can turn off auto-sync in the UI without the controller reverting it; after the incident, restore it in Git. Limitations: Ignored fields are no longer updated by the template afterwards, so they need periodic cleanup.

Common errors and fixes

ErrorOccurred: failed to execute go template …: map has no entry for key "xxx"

Cause: Enabled missingkey=error, the template references parameters the generator does not produce (typos, a missing key in some element, a missing field in a Git file).

argocd appset get NAME
argocd appset generate file.yaml -o yaml

Fix: Correct the key name. Do not access genuinely optional fields directly with .key (it errors under missingkey=error); instead use {{ index . "key" | default "x" }}——index to return a zero value for missing keys, and then fill it with Sprig's default ; after writing, verify with argocd appset generate .

Applications with name: '<no value>-guestbook' appear in the ApplicationSet

Cause: goTemplate is not set to missingkey=error, so missing parameters are rendered as <no value>.

Fix: Add goTemplateOptions: ["missingkey=error"], and delete the wrongly generated applications.

ApplicationSet … contains applications with duplicate name: podinfo-dev

Cause: Two parameter sets render Applications with the same name (for example, in a Matrix whose names do not include the cluster name).

Fix: Include all distinguishing dimensions in the name: '{{.path.basename}}-{{.name}}'.

Helm rendering error: function "normalize" not defined, or the generated name is "-guestbook"

Cause: When deploying the ApplicationSet with a Helm chart, Helm parsed {{ }} first.

Fix: Write it as a Helm string literal: '{{`{{ .cluster | normalize }}`}}-guestbook'.

After templatePatch, syncOptions / source were cleared

Cause: The patch contained an empty parent key (for example, when a condition is not met only spec: remains), so during merging the original field was overwritten with empty.

Fix: Make sure every parent key always has content, or place the whole block inside if ; verify with argocd appset generate -o yaml .

Command-line tasks
1. Without creating any objects, preview which Application names podinfo-demo.yaml would generate.
argocd appset generate podinfo-demo.yaml -o json | jq -r '.[].metadata.name'
2. Check the most recent rendering errors of the ApplicationSet controller.
kubectl -n argocd logs deploy/argocd-applicationset-controller --since=10m | grep -iE "error|failed"
Scenario analysis
Requirement: the dev environment auto-syncs and auto-prunes, while prod allows manual sync only; the two environments have different Helm valueFiles lists (prod has one extra values-prod-secrets.yaml). How do you implement this with one ApplicationSet?

The List (or Git file) generator provides for each environment autoSync (a boolean) and valueFiles (an array); goTemplate: true + missingkey=error; the outer template writes the common fields; templatePatch in {{- if .autoSync}} is used to generate the automated block, and {{- range .valueFiles}} is used to generate the valueFiles list. Parameters come from a trusted repo; for production, add preserveResourcesOnDeletion: true.

Verified teaching videos

▶
Mastering ApplicationSet: Advanced Argo CD Automation - Alexander Matyushentsev, Akuity — CNCF [Cloud Native Computing Foundation]
English · a co-founder of Argo CD explains advanced ApplicationSet usage
▶
Argo CD ApplicationSets Tutorial: Generators, Templates, and Production Design Patterns — Cloud With VarJosh
English · from beginner to production patterns for generators and templates (community channel; details follow this lesson's verification)

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: a three-row parameter table (dev, staging, prod) slides in from the left into a “template” box.
Narration: an ApplicationSet has two parts: generators produce parameters, and the template turns each set of parameters into one Application.
Shot 2 · 25–55s
Visual: {{.env}} in the template is replaced one by one, and three Application cards appear on the right; the “auto-sync” switch on the prod card is turned off by templatePatch.
Narration: Go templates can only replace strings; boolean and object fields are handed to templatePatch.
Shot 3 · 55–90s
Visual: someone manually edits one card; it is reverted a few seconds later, and all the cards disappear when the ApplicationSet is deleted.
Narration: generated applications are owned by the controller: manual changes are reverted, and deleting the ApplicationSet deletes them. In production, turn on preserveResourcesOnDeletion.
or reach a score of ≥ 70% in the “Quiz”

Module 4 · Generators: List, Git directory / file and Cluster

21:00 – 28:00 · Where parameters come from: hand-written lists, directories in the repo, configuration files in the repo, clusters registered in Argo CD
7 minGit polling: 3 minutes by defaultThe local cluster has no Secret★★★★★
Learning objectives
  • Be able to name the parameters each basic generator produces: any key of List, the Git directory's .path.path / .path.basename / .path.segments, the Git file's “flattened fields + path parameters”, and the Cluster's .name / .nameNormalized / .server / .metadata.labels.<key>.
  • Use the Git directory generator's exclude, and the Cluster generator's label selector to control scope; understand that the local cluster (in-cluster) has, by default,no Secret, so it is excluded when selecting by label.
  • Know the refresh mechanism of the Git generator: default 3-minute polling (ARGOCD_APPLICATIONSET_CONTROLLER_REQUEUE_AFTER / requeueAfterSeconds), affected by the repo-server revision cache, and accelerated by a Webhook or a refresh annotation.
Prerequisites: Module 3. Importance:★★★★★

What: the four basic generators

GeneratorInputParameters produced (goTemplate syntax)Typical use
Listelements objects in the elementsYaml (can also be resolved from the parameters of other generators)any key in an element, such as .env,.cluster; values can be strings, booleans, arrays or objectsA small, fixed number of environments; combined with Matrix
Git directoryrepoURL + revision + directories[].path (glob; can use exclude: true exclude).path.path,.path.basename,.path.basenameNormalized,index .path.segments n; optional values → .values.xautomatic discovery of “one directory = one application / environment”
Git filefiles[].path (glob, such as cluster-config/**/config.json)fields of the file content flattened (cluster.name) + .path.* + .path.filenameone config file per environment / cluster, used when there are more fields than the directory name
Clusterclusters registered in Argo CD (argocd labels in the argocd namespace argocd.argoproj.io/secret-type: cluster Secrets).name,.nameNormalized,.server,.project,.metadata.labels.<key>,.metadata.annotations.<key>“register a cluster and a set of applications is installed automatically” (multi-cluster in Hour 4)

Other generators: SCM Provider, Pull Request (Module 6), Matrix, Merge (Module 5), Cluster Decision Resource (reads the decision result of an external CR), Plugin (calls your own HTTP service to return parameters).

Why: which one to choose

  • choose List when explicit is better than implicit: the list of environments itself needs review (prod has only one), and it is written out clearly in the ApplicationSet.
  • choose Git directory when “convention is configuration”: under overlays/ , create a new qa/ directory, and it appears automatically after committing podinfo-qa. The cost is: whoever can create directories in the repo can create applications.
  • choose Git file when each environment needs several parameters: besides the directory name, there are also the cluster address, replica count, owner, etc.
  • choose Cluster when the cluster is the primary dimension: platform components are installed on every cluster and selected by cluster labels (env,region) to select.

How: key details

Git directory generator

generators:
- git:
    repoURL: https://github.com/<you>/gitops-lab.git
    revision: main
    directories:
    - path: apps/podinfo/overlays/*
    - path: apps/podinfo/overlays/experimental   # exclude a directory
      exclude: true
    requeueAfterSeconds: 180                      # optional: polling interval for this ApplicationSet
  • .path.basename is always the rightmost directory name: apps/podinfo/overlays/dev → dev; index .path.segments 1 → podinfo.
  • exclude the rule applies to all directories entries; any matching directory is always excluded.
  • When two Git generators are used in the same Matrix, use pathParamPrefix to distinguish parameter names, otherwise .path will conflict.

Git file generator

Fields in JSON / YAML files are flattened into parameters: {"cluster":{"name":"engineering-dev"}} → .cluster.name; in addition it provides .path.path (the directory where the file is located),.path.basename,.path.filename. A file can be an array; each element of the array produces one parameter set.

Cluster generator and the local cluster

  • clusters: {} selects all clusters,including the local cluster (in-cluster, the cluster where Argo CD runs).
  • By default, the local cluster has no Secret, so it has no labels, and any label selector will exclude it. To let the local cluster take part in label-based selection, you need to declare a cluster Secret for it (step 3 of this module's lab) or edit the local cluster once in the UI.
  • values fields can append fixed parameters to every cluster; when referencing them, add the prefix .values.; flatList: true can pass all clusters as a single list to one Application.
  • To reference labels that contain hyphens, use index: {{ index .metadata.labels "gitops-lab/env" }}.

Refresh: how long after a new Git commit it takes effect

MechanismDelayNotes
Default polling3 minutesset globally by ARGOCD_APPLICATIONSET_CONTROLLER_REQUEUE_AFTER ; a single ApplicationSet uses requeueAfterSeconds
repo-server revision cachemay be longerThe Git generator reads directories and files through repo-server; if the cache expiry is longer than the polling interval, new directories may appear a little later
refresh annotationimmediatelyargocd.argoproj.io/application-set-refresh (any value); bypasses the revision cache and is removed automatically after processing
ApplicationSet Webhookwithin secondsWebhook on the API Server is not the same endpoint: the ApplicationSet controller has its own ClusterIP service and needs a separate Ingress, with the path /api/webhook
Common misconceptions① “The Cluster generator's selection argocd.argoproj.io/secret-type: cluster means all clusters” — this selector precisely excludes the local cluster, which has no Secret. ② “The Git directory generator scans things in the cluster” — it scans the directory structure of the Git repo at the specified revision. ③ “Generator parameters can be used freely in spec.project the project field” — a templated project means whoever can change Git decides which project an application belongs to, so the official security docs require administrators to control all data sources of the generator in that case.

Inputs and outputs of the four generators

Listelements: [{env: dev}, {env: prod}] {env: dev}{env: prod} Git directoryoverlays/* → dev/ staging/ prod/ {path.path: …/overlays/dev, path.basename: dev} × 3 Git file**/config.json {"cluster":{"name":…}} {cluster.name: engineering-dev, path.basename: dev, path.filename …} ClusterCluster Secret (label selection) + local cluster {name: in-cluster, server: https://…, metadata.labels.env: lab} same templateeach parameter set → 1 Applicationmultiple top-level generators = results concatenatedcombining = Matrix / Merge (Module 5)
Figure 4-1: the output of every generator is a “list of parameter sets”, and the template treats them all the same

Why the local cluster is excluded by the label selector

Secret cluster-lab2argocd.argoproj.io/secret-type: clusterenv: labselected by the selector ✓ local cluster (default)no Secret → no labelsselected when clusters: {}any label selector excludes it ✗ declare a Secret for the local clustername: in-clusterserver: https://kubernetes.default.svccan be selected after adding the label ✓
Figure 4-2: step 3 of this lesson's lab declares a Secret for in-cluster and adds the label gitops-lab/managed: "true"

Generator expander: select a generator and observe how parameter sets become Applications

After selecting a generator, click “Expand”: the first column is the real input read by the generator, the second column is the parameter sets produced, and the third column is the Applications rendered from the template name: podinfo-{{…}} In the “Git directory” mode you can tick “add qa directory” or “exclude prod” to simulate changes after a commit.

Input
Parameter sets
Application
Select a generator and click “Expand”.
$ argocd appset generate

Core commands

CommandPurposeNotes
argocd cluster listList the clusters visible to the Cluster generatorthe local cluster appears as in-cluster
kubectl -n argocd get secret -l argocd.argoproj.io/secret-type=cluster --show-labelsView cluster Secrets and labelsThese are the Secrets the Cluster generator selects
kubectl -n argocd label secret S key=valueLabel a clusterA label change triggers the ApplicationSet to regenerate
argocd appset generate FILE -o yamlPreview the generated result
kubectl -n argocd annotate appset NAME argocd.argoproj.io/application-set-refresh=trueRefresh immediately after a new Git commitNo need to wait for the 3-minute polling
argocd cluster list
kubectl -n argocd get secret -l argocd.argoproj.io/secret-type=cluster --show-labels
SERVER                          NAME        VERSION  STATUS      MESSAGE  PROJECT
https://kubernetes.default.svc  in-cluster  1.37     Successful
No resources found in argocd namespace.

How to verify: The second command returns nothing, which is evidence that “the local cluster has no Secret”. Common mistakes: Assuming argocd cluster list each line in the list corresponds to a Secret.

Lab 4: Git directory, Git file and Cluster generators (about 7 minutes, mainly preview)

Git directory generator: scan overlays (preview only, no creation — the real go-live is in Module 8)
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: gen-dir
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - git:
      repoURL: https://github.com/<you>/gitops-lab.git
      revision: main
      directories:
      - path: apps/podinfo/overlays/*
  template:
    metadata:
      name: 'podinfo-{{.path.basename}}'
      labels:
        env: '{{.path.basename}}'
    spec:
      project: default
      source:
        repoURL: https://github.com/<you>/gitops-lab.git
        targetRevision: main
        path: '{{.path.path}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: 'podinfo-{{.path.basename}}'
cd ~/appset-lab && argocd appset generate gen-dir.yaml
NAME                    PROJECT  SYNCPOLICY  …  PATH
argocd/podinfo-dev      default  Manual      …  apps/podinfo/overlays/dev
argocd/podinfo-prod     default  Manual      …  apps/podinfo/overlays/prod
argocd/podinfo-staging  default  Manual      …  apps/podinfo/overlays/staging

The generated names are exactly the same as the three existing Applications— if you apply now, it would take over the existing applications and “fight” with the root app. This is exactly why Module 8 migrates step by step.

Git file generator: read config.json from the official example repository (preview only)
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: gen-files
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - git:
      repoURL: https://github.com/argoproj/argo-cd.git
      revision: HEAD
      files:
      - path: "applicationset/examples/git-generator-files-discovery/cluster-config/**/config.json"
  template:
    metadata:
      name: 'files-{{.cluster.name}}'
      annotations:
        owner: '{{.cluster.owner}}'
        source-file: '{{.path.path}}/{{.path.filename}}'
    spec:
      project: default
      source:
        repoURL: https://github.com/argoproj/argo-cd.git
        targetRevision: HEAD
        path: applicationset/examples/git-generator-files-discovery/apps/guestbook
      destination:
        server: https://kubernetes.default.svc
        namespace: 'files-{{.path.basename}}'
argocd appset generate gen-files.yaml -o yaml | grep -E 'name: files-|owner:|source-file:'
      owner: cluster-admin@company.com
      source-file: applicationset/examples/git-generator-files-discovery/cluster-config/engineering/dev/config.json
    name: files-engineering-dev
      owner: cluster-admin@company.com
      source-file: applicationset/examples/git-generator-files-discovery/cluster-config/engineering/prod/config.json
    name: files-engineering-prod

The destination in the official example is a fictitious address https://1.2.3.4; here it is changed to the local cluster, just to observe parameter flattening. The example file follows the current content of the argo-cd repo.

Cluster generator: declare a Secret for the local cluster and label it
apiVersion: v1
kind: Secret
metadata:
  name: in-cluster
  namespace: argocd
  labels:
    argocd.argoproj.io/secret-type: cluster
    gitops-lab/managed: "true"
    env: lab
type: Opaque
stringData:
  name: in-cluster
  server: https://kubernetes.default.svc
  config: '{"tlsClientConfig":{"insecure":false}}'
kubectl apply -f in-cluster-secret.yaml
argocd cluster list
cat > gen-cluster.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: gen-cluster
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - clusters:
      selector:
        matchLabels:
          gitops-lab/managed: "true"
  template:
    metadata:
      name: 'cluster-{{.nameNormalized}}'
      labels:
        env: '{{.metadata.labels.env}}'
    spec:
      project: default
      source:
        repoURL: https://github.com/argoproj/argocd-example-apps.git
        targetRevision: HEAD
        path: guestbook
      destination:
        server: '{{.server}}'
        namespace: guestbook
EOF
argocd appset generate gen-cluster.yaml
secret/in-cluster created
SERVER                          NAME        VERSION  STATUS      MESSAGE  PROJECT
https://kubernetes.default.svc  in-cluster  1.37     Successful
NAME                       PROJECT  SYNCPOLICY  …  PATH
argocd/cluster-in-cluster  default  Manual      …  guestbook

Remove the gitops-lab/managed label from the Secret and preview again; the result becomes empty — the label selector excludes the local cluster that has no labels. Keep this Secret: the Matrix in Module 5 and the multi-cluster content in Hour 4 both select clusters by this label.

Cleanup: this module is preview only, so there is no need to clean up the ApplicationSet; the ~/appset-lab/ files in it can be kept for reference.

Case 1: a new cluster installs platform components automatically on go-live

Problem: Every time a new AKS cluster is created, a dozen or so platform Applications had to be created by hand. Approach: The platform ApplicationSet uses the Cluster generator and selects the label platform: enabled; Terraform writes this label when it registers the cluster. Configuration: the cluster Secret's env,region label is passed via .metadata.labels into the Helm values. Limitations: Removing the label deletes these applications; the platform ApplicationSet must enable preserveResourcesOnDeletion.

Case 2: a Git directory generator was used to “quietly” add applications

Problem: A developer created a new directory in the config repo, and the Git directory generator automatically created an application pointing at the production cluster. Approach: Set CODEOWNERS on apps/ ; the ApplicationSet's project is hard-coded to a restricted project, with no parameter templating; the directory generator scans only explicit prefixes. Limitations: See “Templated project field” in the official ApplicationSet Security docs.

Case 3: a new directory took 10 minutes to appear

Problem: A new overlay was committed, but the application was slow to generate. Approach: Investigation showed that the repo-server revision cache time was longer than the ApplicationSet polling interval; configure a Webhook for the ApplicationSet controller (with a separate Ingress), and use the refresh annotation in emergencies.

Common errors and fixes

The ApplicationSet status is normal, but 0 Applications were generated (Cluster generator)

Cause: A label selector was used, but the target is the local cluster, which has no Secret; or the label value's type or spelling does not match.

kubectl -n argocd get secret -l argocd.argoproj.io/secret-type=cluster --show-labels

Fix: Declare a Secret for the local cluster and add the label (lab step 3), or switch to clusters: {}.

A newly added overlay directory took a long time to generate its application

Cause: Default 3-minute polling plus the repo-server revision cache.

kubectl -n argocd annotate appset NAME argocd.argoproj.io/application-set-refresh=true --overwrite

Fix: Configure an ApplicationSet Webhook, or shorten requeueAfterSeconds (watch the rate limits of the Git hosting provider).

application destination server 'https://1.2.3.4' and namespace 'guestbook' do not match any of the allowed destinations / cluster not found

Cause: The cluster address in the Git file is not registered in Argo CD. The official docs stress that clusters referenced by a generator must already be defined.

Fix: First argocd cluster add (Hour 4), or switch to the Cluster generator to take addresses from registered clusters.

template: … map has no entry for key "path" (two Git generators used in a Matrix)

Cause: The .path parameters of the two Git generators conflict or overwrite each other.

Fix: Set pathParamPrefix: myRepo on one of them, and use .myRepo.path.basename in the template.

Command-line tasks
1. Add the label in-cluster to the cluster Secret region=local, and confirm that the ApplicationSet regenerates immediately.
kubectl -n argocd label secret in-cluster region=local --overwrite
kubectl -n argocd logs deploy/argocd-applicationset-controller --since=2m | grep -i "generated"
2. Use one command to list the overlay directories that the Git directory generator will scan (in the local repo).
cd ~/gitops-lab && ls -d apps/podinfo/overlays/*/
Scenario analysis
A team has 3 environments, each with different cluster addresses, replica counts and on-call owners, and wants “adding an environment should only require adding one file”. Which generator should you choose? Where do the files go? What safety considerations apply?

Git file generator: one envs/<env>/config.yaml per environment (cluster name, replica count, owner); the template references the flattened fields; it is best to use the cluster name for the cluster address and register the cluster in advance. Security: whoever can change that directory can create applications, so CODEOWNERS is needed; project do not template the project, or only allow a restricted project; enable missingkey=error to prevent wrong applications being generated when fields are missing.

Verified teaching videos

▶
Manage More Clusters with Less Hassle, with Argo CD Application Sets - Jonathan West & Kshama Jain — CNCF [Cloud Native Computing Foundation]
English · an ApplicationSet maintainer covers the List / Cluster / Git generators and multi-cluster
▶
ArgoCD 8: Application set — Chalk Talk with Amit
English · an introductory demo from a community channel (follow the fields verified in this lesson)

Official docs

Video storyboard (about 80 seconds)

Shot 1 · 0–20s
Visual: four icons (list, folder, file, cluster) light up in turn.
Narration: four basic generators answer the same question: where do the parameters come from?
Shot 2 · 20–50s
Visual: a new qa folder appears under overlays; after the three-minute timer runs out, the podinfo-qa card appears.
Narration: the Git directory generator discovers applications automatically by directory, polling every three minutes by default; a Webhook can also trigger it immediately.
Shot 3 · 50–80s
Visual: the local cluster icon has no label tag and is filtered out by the selector; after a Secret and a label are added, it is selected.
Narration: the Cluster generator reads cluster Secrets; the local cluster has no Secret by default, so it is excluded when selecting by label.
or reach a score of ≥ 70% in the “Quiz”

Module 5 · Composite generators: Matrix and Merge

28:00 – 35:00 · Matrix does a Cartesian product (environments × clusters); Merge merges by key (base parameters + a few overrides)
7 minCore animation for this lessonMatrix takes only 2 child generators · can nest only one level★★★★★
Learning objectives
  • Predict the output count and parameters of a Matrix: if child generator A produces m sets and B produces n sets, you get m × n sets, each being the union of A's and B's parameters.
  • Remember the 6 restrictions of Matrix: it supports only two child generators; each array element can contain only one generator; the child's template is not processed; composite generators can nest only one level; a child generator that consumes parameters must come after the one producing them; and they cannot reference each other.
  • Use Merge's mergeKeys to patch a few parameter sets: the first (base) generator is authoritative, and later generators only override parameter sets whose keys match; the later the generator, the higher its priority; non-matching parameter sets are discarded.
Prerequisites: The four generators from Module 4 and their parameter names. Importance:★★★★★

What: the Matrix generator

Matrix takes the outputs of two child generators and does a Cartesian product: each set of A's parameters is combined with each set of B's parameters into a new set. The typical use is “Git directory (applications / environments) × Cluster (clusters)” — exactly the combination recommended by the official Cluster Bootstrapping docs: label a cluster with region: eu,type: workload label, and it automatically gets all the applications in the directories.

generators:
- matrix:
    generators:
    - git:                                   # child generator 1: 3 sets {path.*}
        repoURL: https://github.com/<you>/gitops-lab.git
        revision: main
        directories:
        - path: apps/podinfo/overlays/*
    - clusters:                              # child generator 2: n sets {name, server, metadata.labels.*}
        selector:
          matchLabels:
            gitops-lab/managed: "true"
template:
  metadata:
    name: 'podinfo-{{.path.basename}}-{{.nameNormalized}}'   # the name must contain both dimensions
  spec:
    destination:
      server: '{{.server}}'
      namespace: 'podinfo-{{.path.basename}}'

Parameter passing: a later child generator can use the parameters of an earlier one

A field of the second child generator can reference a parameter produced by the first; for example, first read with the Git file generator {{.env}}, and then in the Cluster generator's selector write env: '{{.env}}', so that each config file only matches the clusters of its environment. Rule: the consumer must come after the producer, and the two cannot consume each other (circular dependency).

Matrix restrictions (official docs, Restrictions)

  1. Only supports combining two child generators; for three dimensions, put two of them into an inner Matrix / Merge first (only one level of nesting is allowed).
  2. Each array element may only contain one generator (writing - list: … git: … in the same element errors out at generation time, though it passes API validation).
  3. The template on child generators is not processed.
  4. Composite generators (matrix / merge) can be nested only once; a third level has no effect.
  5. Parameter consumers must come after producers.
  6. Two child generators cannot consume each other's parameters.

When combining two Git generators, use pathParamPrefix to distinguish .path; if two child generators produce parameters with the same name, the later one overrides the earlier, so choose names deliberately to avoid clashes.

What: the Merge generator

Merge uses the output of the first child generator (the base) as authoritative; a subsequent child generator's parameter sets whose values for mergeKeys match a base parameter set override the corresponding fields; non-matching parameter sets are discarded; the override order is bottom-up, so the value from the 3rd generator takes precedence over the 2nd. Suitable for “most clusters use defaults, a few clusters get patches”.

generators:
- merge:
    mergeKeys:
    - env
    generators:
    - list:                     # base: default values for all environments
        elements:
        - {env: dev,     autoSync: true,  replicas: "1"}
        - {env: staging, autoSync: true,  replicas: "2"}
        - {env: prod,    autoSync: true,  replicas: "3"}
    - list:                     # override: only changes prod
        elements:
        - {env: prod, autoSync: false}
    - list:                     # matches no base parameter set → discarded
        elements:
        - {env: qa, autoSync: true}
MatrixMerge
Countm × n= number of base generators
Parameter mergeunion of each pair (a, b)override after matching by mergeKeys
Number of child generators22 or more
Typical scenarioapplications × clusters, environments × regionsdefaults + exceptions (e.g., one cluster enables Kafka, prod disables auto-sync)

When: when to use composite generators

When both dimensions need automatic discovery (new directories and new clusters both take effect automatically), use Matrix; when there are only a few exceptions, the Merge or Cluster generator's values is clearer. The deeper the composition, the harder the result is to predict, so always use argocd appset generate to check the output in the PR.

Common misconceptions① “Matrix can take three generators”: no, only two; a third dimension must be nested. ② “Merge brings in new entries from the overriding generators”: no, it only overrides entries that match the base and discards the rest. ③ “Using only the directory name in the name is enough”: under Matrix, one directory maps to multiple clusters, and a name without the cluster dimension leads to duplicate-name errors.

Matrix: 3 directories × 2 clusters = 6 Applications

Child generator 1: Git directory dev staging prod Child generator 2: Cluster (gitops-lab/managed=true) in-cluster (lab) lab2 (Hour 4) podinfo-dev-in-cluster podinfo-dev-lab2 podinfo-staging-in-cluster podinfo-staging-lab2 podinfo-prod-in-cluster podinfo-prod-lab2 Each cell's parameters = row parameters ∪ column parameters: {path.basename: prod, name: lab2, server: https://…, metadata.labels.env: …} In Hour 4, add the label gitops-lab/managed=true to the Secret for lab2, and a column appears automatically on the right, without changing the ApplicationSet
Figure 5-1: Matrix is “rows × columns”; the name template must include both the row and column dimensions

Merge: base + overrides, aligned by mergeKeys

Base (generator 1) env=dev autoSync=true env=staging autoSync=true env=prod autoSync=true Overrides (generators 2, 3) env=prod autoSync=false env=qa (no match → discarded) Result dev autoSync=true staging autoSync=true prod autoSync=false (overridden)
Figure 5-2: the number of Merge results equals the number of base generators; the later the generator, the higher its priority

Core animation: the generator expands parameters into Applications (Matrix combination + Merge override)

On the left is child generator 1 (Git directory), and on top is child generator 2 (Cluster). Click “Expand one by one”: the controller generates parameter sets as rows × columns and renders the names; the checkboxes change the inputs (add a directory, register lab2, label selector, name template), so you can observe the number of results and conflicts. Switch to Merge mode to observe mergeKeys alignment and discards.

Ready.
$ argocd appset generate podinfo-matrix.yaml

Core commands: predict and verify combined results

CommandPurposeNotes
argocd appset generate F -o json | jq lengthNumber of resultsshould equal m × n (Matrix) or the number of base sets (Merge)
argocd appset generate F -o json | jq -r '.[].metadata.name' | sort | uniq -dFind duplicate namesAny output will report duplicate name
argocd appset get NAMECheck the ErrorOccurred conditionComposition limits (three levels of nesting, multiple generators in one element) error out here
cd ~/appset-lab
argocd appset generate podinfo-matrix.yaml -o json | jq -r '.[] | [.metadata.name, .spec.destination.server, .spec.destination.namespace] | @tsv'
podinfo-dev-in-cluster	https://kubernetes.default.svc	podinfo-dev
podinfo-prod-in-cluster	https://kubernetes.default.svc	podinfo-prod
podinfo-staging-in-cluster	https://kubernetes.default.svc	podinfo-staging

How to verify: 3 directories × 1 labeled cluster = 3. After registering lab2 in Hour 4 and labeling it, the same command outputs 6 lines. Common mistakes: In the second child generator, a parameter is referenced that the first child generator has not produced yet (the order is reversed).

Lab 5: preview a Matrix (overlay × cluster) and a Merge (default + exceptions) (about 6 minutes)

Write a Matrix ApplicationSet (depends on the labeled in-cluster Secret from the Module 4 lab)
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: podinfo-matrix
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - matrix:
      generators:
      - git:
          repoURL: https://github.com/<you>/gitops-lab.git
          revision: main
          directories:
          - path: apps/podinfo/overlays/*
      - clusters:
          selector:
            matchLabels:
              gitops-lab/managed: "true"
  template:
    metadata:
      name: 'podinfo-{{.path.basename}}-{{.nameNormalized}}'
      labels:
        env: '{{.path.basename}}'
        cluster: '{{.nameNormalized}}'
    spec:
      project: default
      source:
        repoURL: https://github.com/<you>/gitops-lab.git
        targetRevision: main
        path: '{{.path.path}}'
      destination:
        server: '{{.server}}'
        namespace: 'podinfo-{{.path.basename}}'
cd ~/appset-lab
argocd appset generate podinfo-matrix.yaml

Preview only, do not apply: these applications would be deployed to the same namespace with the same resource names as the existing podinfo-*, so creating them for real would produce SharedResourceWarning.

Verify “the name must contain both dimensions”: change the name to 'podinfo-{{.path.basename}}' and preview. With only one cluster there is no conflict, but it is a time bomb:
sed "s/-{{.nameNormalized}}'$/'/" podinfo-matrix.yaml > bad-name.yaml
grep "name: 'podinfo" bad-name.yaml
argocd appset generate bad-name.yaml -o json | jq -r '.[].metadata.name' | sort | uniq -d   # empty for now; once lab2 exists it will print duplicate names
Experience the ordering restriction: swap the order of the two child generators, and make the git generator reference {{.name}} (for example path: 'apps/podinfo/overlays/{{.name}}'). The preview will error out or return an empty result. Think about it: why must the producer come first? (Parameters are evaluated in the order of the child generators.)
Merge: default auto-sync, with prod as the exception
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: podinfo-merge
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - merge:
      mergeKeys:
      - env
      generators:
      - list:
          elements:
          - {env: dev, autoSync: true}
          - {env: staging, autoSync: true}
          - {env: prod, autoSync: true}
      - list:
          elements:
          - {env: prod, autoSync: false}
          - {env: qa, autoSync: true}
  template:
    metadata:
      name: 'merge-{{.env}}'
    spec:
      project: default
      source:
        repoURL: https://github.com/<you>/gitops-lab.git
        targetRevision: main
        path: 'apps/podinfo/overlays/{{.env}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: 'podinfo-{{.env}}'
  templatePatch: |
    {{- if .autoSync }}
    spec:
      syncPolicy:
        automated: {}
    {{- end }}
argocd appset generate podinfo-merge.yaml
NAME                  PROJECT  SYNCPOLICY  …  PATH
argocd/merge-dev      default  Auto        …  apps/podinfo/overlays/dev
argocd/merge-prod     default  Manual      …  apps/podinfo/overlays/prod
argocd/merge-staging  default  Auto        …  apps/podinfo/overlays/staging

qa does not appear: it matches none of the env, so it is discarded. The whole templatePatch is wrapped in if , so when the condition is not met the patch is empty, and the “empty spec clears fields” problem does not occur.

Case 1: 50 clusters × 20 platform components

Problem: Hand-writing 1000 Applications is not maintainable. Approach: Matrix (Git directory platform/* × Cluster selection platform: enabled), with the name '{{.path.basename}}-{{.name}}'; for components that are installed only on prod clusters, use a Git file in the directory plus the second child generator referencing {{.tier}} as the selector. Limitations: One template change affects 1000 applications, so RollingSync or splitting into multiple ApplicationSets is needed.

Case 2: only two clusters need different Helm parameters

Approach: Merge: the base Cluster generator carries values.kafka: 'true', a second Cluster generator overrides some clusters selected by label to 'false', and a third List generator uses server to enable Redis for one cluster (the same as the official Merge docs example). Limitations: The override logic is hidden inside the generators, so attach the generate output to the PR.

Case 3: a three-dimensional “application × environment × region” requirement

Approach: One child generator of the outer Matrix is itself a Matrix (one level of nesting, which is allowed), or “environment × region” is written into a Git file to make it one dimension. Limitations: No third level of nesting is possible; when readability drops sharply, consider splitting into multiple ApplicationSets.

Common errors and fixes

ApplicationSet … contains applications with duplicate name: podinfo-dev

Cause: The Matrix name template does not include the second dimension.

Fix: Include the parameters of both child generators in the name, for example 'podinfo-{{.path.basename}}-{{.nameNormalized}}'.

After three child generators are written in a Matrix, ErrorOccurred=True (the message says the number of child generators does not meet the requirement)

Cause: Three child generators were written in the Matrix.

Fix: Put two of them into an inner matrix / merge (only one level of nesting is allowed), or use a Git file to merge the dimensions.

The Matrix only produced the result of one child generator / a child generator is “ignored”

Cause: Two generators were written in the same array element (- list: … git: …), or template was written on a child generator (Matrix does not process it).

Fix: Give each generator its own array element; move template differences to the outer template / templatePatch.

A Merge result is missing an override entry (for example qa)

Cause: This is how Merge is designed: it only overrides parameter sets that match the base generator's mergeKeys; the rest are discarded.

Fix: If you need a new entry, add it to the base generator.

map has no entry for key "name" (the first Matrix child generator references a Cluster parameter)

Cause: The parameter consumer comes before the producer.

Fix: Swap the order of the child generators.

Command-line tasks
1. Preview podinfo-matrix.yaml and count the generated applications per cluster.
argocd appset generate podinfo-matrix.yaml -o json | jq -r '.[].metadata.labels.cluster' | sort | uniq -c
2. After registering lab2 in Hour 4, make it enter the Matrix.
kubectl -n argocd get secret -l argocd.argoproj.io/secret-type=cluster
kubectl -n argocd label secret <lab2 cluster Secret name> gitops-lab/managed=true
Scenario analysis
There are 4 microservice directories and 3 clusters (one each for dev, staging and prod). Requirement: each service should be deployed only to the cluster of the environment with the same name as its overlay, not 4 × 3 × 3. How would you design this?

Do not Matrix three dimensions. The directory structure apps/<svc>/overlays/<env>, use the Git directory generator to scan apps/*/overlays/* (each directory gives one set of parameters: index .path.segments 1 = service,.path.basename = environment), then Matrix one Cluster generator, with the selector written as env: '{{.path.basename}}' (parameter passing; Git first). Result = 4 × 3 directories, each matching only one cluster = 12 applications.

Verified teaching videos

▶
Multi-cluster, multi-apps, multi-value deployments using Argo CD Application Sets - Kostis Kapelonis — CNCF [Cloud Native Computing Foundation]
English · managing “multi-cluster × multi-application × multi-value” with composite generators
▶
ArgoCD: Setting up multicluster environment [Matrix Generator] — Chalk Talk with Amit
English · a Matrix generator multi-cluster demo (community channel)

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: three directory cards on the left, two cluster cards on top, and a blank table in the middle.
Narration: the Matrix generator does multiplication: each directory is paired with each cluster; three times two is six.
Shot 2 · 25–55s
Visual: the table lights up cell by cell, each cell showing the merged parameters and the Application name; when a name lacks the cluster dimension, two cells turn red and show duplicate name.
Narration: each cell's parameters are the union of the parameters on both sides; the name must contain both dimensions, or names will collide.
Shot 3 · 55–90s
Visual: switch to Merge: three rows of defaults, one prod override slides in to line up, and the qa override fades out after finding no matching object.
Narration: Merge is patching: the first generator is authoritative, a few entries are overridden by merge key, and non-matching ones are discarded outright.
or reach a score of ≥ 70% in the “Quiz”

Module 6 · SCM Provider and Pull Request generator: preview environments

35:00 – 42:00 · Make the Git hosting platform's API a source of parameters: every repo in the organization and every PR in a repo can automatically become an Application
7 minPR polling defaults to 30 minutesNeeds a GitHub token · only administrators can write ApplicationSets★★★★☆
Learning objectives
  • Distinguish the SCM Provider generator (scans repos in the organization) from the Pull Request generator (scans open PRs in the repo) and state the parameters of each.
  • Set up PR preview environments for gitops-lab: PRs with the preview label → podinfo-pr-<number> application that deploys the PR's head_sha, which is deleted automatically after the PR closes.
  • Configure the GitHub token correctly (fine-grained, read-only, minimal repository scope),tokenRef strict mode, allowed SCM addresses, and understand polling and the ApplicationSet Webhook.
Prerequisites: Modules 3–4; GitHub PRs and labels (GitHub lesson). Importance:★★★★☆

What: two generators that “read the SCM API”

SCM Provider generatorPull Request generator
What they discoverin an organization / group,repositories (can scan all branches)in a repository,open PRs / MRs
Supported platformsGitHub, GitLab, Gitea, Bitbucket Server / Cloud, Azure DevOps, AWS CodeCommit (Alpha)GitHub, GitLab, Gitea, Bitbucket Server / Cloud, Azure DevOps
Required GitHub fieldsorganization (organization name; use multiple generators for multiple organizations)owner (organization or user),repo
filtersfilters: repositoryMatch,pathsExist,pathsDoNotExist,labelMatch (GitHub uses repository topics),branchMatchGitHub / GitLab: labels (must include all labels); filters: branchMatch,targetBranchMatch,titleMatch
Main parameters.organization .repository .url .branch .branchNormalized .sha .short_sha .labels.number .title .branch .branch_slug .target_branch .head_sha .head_short_sha .labels .author
Typical useAn organization with “one repo per microservice”; when a repo contains a deploy/ directory, it is deployed automaticallyCreate a temporary preview environment for each PR, destroyed when the PR closes

Why: the value of preview environments

Reviewers do not only look at the diff; they open a really running environment to verify the change. The environment's lifecycle matches the PR exactly, with no manual request or cleanup. For a config repo, PR previews show “what happens when the overlay changes” before merging.

How: how the PR generator works

  1. The controller calls the GitHub API every requeueAfterSeconds (default 1800 seconds) to list open PRs; once an ApplicationSet Webhook is configured, the PR opened / closed / reopened / labeled / unlabeled / synchronized events trigger immediately.
  2. Filtered by labels and filters , each PR produces one set of parameters.
  3. The template usually uses targetRevision: '{{.head_sha}}' to deploy the PR's latest commit exactly, with the name and namespace carrying {{.number}}.
  4. When the PR closes (or the label is removed), no more parameters are produced → the Application is deleted; if the Application has a resources-finalizer, its resources are deleted with it.

GitHub token: what permissions are needed

  • tokenRef Optional: without one, access is anonymous and you can only see public repos, and GitHub's rate limit for unauthenticated REST requests is very low (60 per hour per IP), so it is quickly exhausted with short polling intervals.
  • Recommended fine-grained personal access token or GitHub App (appSecretName, a Secret in repo-creds format): authorize only gitops-lab one repository, with permission Pull requests: Read-only (Metadata read-only is included automatically); for private repositories, add Contents: Read-only. The PR generator only reads the API and does not need write permissions.
  • Argo CD fetching the PR commits uses repository credentials (the repo credentials configured in Hour 1), and has nothing to do with tokenRef .

Security switches (argocd-cmd-params-cm)

KeyPurpose
applicationsetcontroller.enable.tokenref.strict.mode: "true"tokenRef can only reference a Secret with the label argocd.argoproj.io/secret-type: scm-creds Secret, which prevents the ApplicationSet from sending any Secret in the argocd namespace as a token to an external address (strongly recommended by the official docs).
applicationsetcontroller.allowed.scm.providersWhitelist of allowed SCM API addresses (such as https://git.mydomain.com/); other addresses are rejected.
applicationsetcontroller.enable.scm.providers: "false"Completely disable the SCM Provider and PR generators.
Security reminder (official Security docs) Only administrators can create or modify ApplicationSets: a generator can read Secrets in the argocd namespace and send them as an auth header to api address given in the field. If the PR generator's project field is templated, only administrators may be allowed to create PRs. This lesson hard-codes project and uses the preview label as an “approval gate”: on GitHub, only people with triage or higher permission can label a PR.

When: when to use

PR generator: use it when you need to validate configuration or application changes per PR and the cluster has the capacity to host several temporary environments. SCM Provider: use it when the organization follows “one repo per service” and wants “a repo with an agreed directory goes live automatically”, provided the organization governs repository creation. Both depend on the availability and rate limits of an external API, so in production configure a Webhook and a reasonable polling interval.

Common misconceptions① “The PR generator uses Argo CD's Git Webhook”: the ApplicationSet controller has its own Webhook service, which needs a separate Ingress. ② “The namespace is also deleted when the PR closes” — the CreateNamespace=true namespace it creates is not deleted along with the Application. ③ “Giving the token full repo permissions is the easiest”: the PR generator only needs to read PRs, so least privilege is enough.

Full path of a PR preview environment

GitHub: gitops-labPR #7 branch demo-msglabel previewhead_sha 9c41e2a… ① REST API polling or Webhook ApplicationSet controllertokenRef → Secret github-token(scm-creds label, strict mode)② label filter → {number: 7, …}③ render podinfo-pr-7 Application podinfo-pr-7targetRevision: 9c41e2a…path: overlays/devkustomize.namespace: podinfo-pr-7④ sync to ns podinfo-pr-7 Lifecycle PR opened + label added→ create application push new commit→ head_sha changes → update targetRevision remove label / close / merge→ delete application (finalizer cascade) leftover namespace→ clean up periodically
Figure 6-1: the PR generator turns “the existence of a PR” into “the existence of an application”

SCM Provider: organization → repository → application

GitHub organization myorgsvc-a (has deploy/)svc-b (has deploy/) · docs (none) filtersrepositoryMatch: ^svc-pathsExist: [deploy/kustomization.yaml] Application × 2svc-a (.repository/.url/.branch)svc-b
Figure 6-2: the SCM Provider generator discovers repos by organization; the docs repo is filtered out by pathsExist

PR lifecycle simulation: add label → generate → push → close

Toggle “Webhook” to observe the difference in trigger delay (polling is timed at requeueAfterSeconds: 60 , the actual default value is 1800 seconds). Below each step, the terminal shows what you would see in argocd app list and the controller logs (example output).

Ready: there are no open PRs in gitops-lab.
$ argocd app list -l gitops-lab/group=preview

Core commands

CommandPurposeNotes
kubectl -n argocd create secret generic github-token --from-literal=token=…Save the tokenthen add the label argocd.argoproj.io/secret-type=scm-creds (needed in strict mode)
gh label create previewCreate the label in the repoGitHub CLI
gh pr create --label preview …Create a PR with the label
gh pr close N --delete-branchClose the PRThe preview application is deleted afterwards
curl -H "Authorization: Bearer $T" https://api.github.com/rate_limitCheck the remaining token quotaTroubleshoot rate limiting
read -rs GH_TOKEN      # paste the fine-grained token (not echoed)
kubectl -n argocd create secret generic github-token --from-literal=token="$GH_TOKEN"
kubectl -n argocd label secret github-token argocd.argoproj.io/secret-type=scm-creds
curl -s -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/rate_limit | jq '.resources.core'
unset GH_TOKEN
secret/github-token created
secret/github-token labeled
{
  "limit": 5000,
  "used": 3,
  "remaining": 4997,
  "reset": 1763380000
}

How to verify: A limit of 5000 indicates the token is valid (60 when unauthenticated). Common mistakes: After enabling strict mode, forgetting to add the scm-creds label to the Secret. Production use: Token Secrets are managed by External Secrets / Sealed Secrets (Hour 5); do not commit plaintext to Git.

Enable tokenRef strict mode (Helm values)

configs:
  params:
    applicationsetcontroller.enable.tokenref.strict.mode: true
helm upgrade argocd argo/argo-cd --version 10.18.0 -n argocd -f ~/gitops-lab/bootstrap/argocd-values.yaml
kubectl -n argocd rollout status deploy/argocd-applicationset-controller

Lab 6: create a preview environment for a PR in gitops-lab (about 8 minutes; requires a GitHub token and the gh CLI)

Prepare the token and label: create a fine-grained token on GitHub (Repository access: Only select repositories → gitops-lab; Permissions: Pull requests = Read-only), and create the github-token Secret following the “Commands” page; then create the label in the repo:
cd ~/gitops-lab && gh label create preview --description "deploy a preview environment" --color 1d63ed
Commit the PR ApplicationSet to (synced by the root app, fully GitOps)
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: podinfo-preview
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - pullRequest:
      github:
        owner: <you>
        repo: gitops-lab
        tokenRef:
          secretName: github-token
          key: token
        labels:
        - preview
      requeueAfterSeconds: 60          # for the lab; in production, configure a Webhook and keep a longer interval
  template:
    metadata:
      name: 'podinfo-pr-{{.number}}'
      labels:
        gitops-lab/group: preview
      annotations:
        gitops-lab/pr-branch: '{{.branch}}'
      finalizers:
      - resources-finalizer.argocd.argoproj.io   # clean up resources when the PR closes
    spec:
      project: default
      source:
        repoURL: https://github.com/<you>/gitops-lab.git
        targetRevision: '{{.head_sha}}'
        path: apps/podinfo/overlays/dev
        kustomize:
          namespace: 'podinfo-pr-{{.number}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: 'podinfo-pr-{{.number}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
        - CreateNamespace=true
git add argocd/appsets/podinfo-preview.yaml
git commit -m "appsets: podinfo PR preview environments" && git push
argocd app sync root      # or wait for auto-sync
argocd appset get podinfo-preview
Open a PR with the preview label
git switch -c demo-msg
sed -i 's/hello from dev/hello from PR preview/' apps/podinfo/overlays/dev/kustomization.yaml
git commit -am "demo: change dev message" && git push -u origin demo-msg
gh pr create --title "demo: preview message" --body "preview test" --label preview
sleep 75; argocd app list -l gitops-lab/group=preview
https://github.com/<you>/gitops-lab/pull/7
NAME                   CLUSTER                         NAMESPACE       PROJECT  STATUS  HEALTH   SYNCPOLICY
argocd/podinfo-pr-7    https://kubernetes.default.svc  podinfo-pr-7    default  Synced  Healthy  Auto-Prune
Visit the preview environment
PR=$(gh pr view --json number -q .number)
kubectl -n podinfo-pr-$PR port-forward svc/podinfo 9898:9898 &
sleep 2; curl -s localhost:9898 | jq -r .message; kill %1
hello from PR preview
Push a new commit and watch head_sha update
sed -i 's/hello from PR preview/hello from PR preview v2/' apps/podinfo/overlays/dev/kustomization.yaml
git commit -am "demo: v2" && git push
sleep 75; argocd app get podinfo-pr-$PR -o json | jq -r .spec.source.targetRevision; git rev-parse HEAD

If the two SHAs are the same, the preview application has followed the PR's latest commit.

Close the PR and watch it be destroyed automatically (do not merge, to avoid the change entering main)
gh pr close $PR --delete-branch
git switch main && git branch -D demo-msg
sleep 75; argocd app list -l gitops-lab/group=preview; kubectl get ns podinfo-pr-$PR
kubectl delete ns podinfo-pr-$PR    # namespaces created by CreateNamespace must be cleaned up manually
NAME  CLUSTER  NAMESPACE  PROJECT  STATUS  HEALTH  SYNCPOLICY  CONDITIONS  REPO  PATH  TARGET
NAME           STATUS   AGE
podinfo-pr-7   Active   6m
namespace "podinfo-pr-7" deleted
(Read-only) SCM Provider example: if you have a GitHub organization, you can preview using the syntax below; skip this if you use a personal account.
generators:
- scmProvider:
    cloneProtocol: https
    github:
      organization: myorg
      tokenRef: {secretName: github-token, key: token}
    filters:
    - repositoryMatch: ^svc-
      pathsExist: [deploy/kustomization.yaml]
template:
  metadata:
    name: '{{.repository}}'
  spec:
    source: {repoURL: '{{.url}}', targetRevision: '{{.branch}}', path: deploy}
Retention and cleanupargocd/appsets/podinfo-preview.yaml It can be kept; PRs in later lessons can all get preview environments. When it is no longer needed, delete the file from Git (the root app will delete the ApplicationSet). Remember to rotate the Secret after the token expires.

Case 1: the frontend team gets one preview URL per PR

Problem: Design reviews need a clickable environment. Approach: PR generator + Helm parameters ingress.host: pr-{{.number}}.preview.example.com (wildcard DNS + wildcard certificate); CI builds pr-{{.number}}-{{.head_short_sha}} the image tag, referenced in the template as head_short_sha . Limitations: The image build must finish before Argo CD syncs, otherwise there is a brief ImagePullBackOff; you can have CI apply the preview label only after the build completes.

Case 2: GitHub API rate limiting stopped all ApplicationSet updates

Problem: 20 PR generators all used the same personal token and polled every 30 seconds, which triggered rate limits. Approach: Switch to a GitHub App (each installation has its own quota), change polling back to the 30-minute default, and configure a Webhook. Limitations: The Webhook requires GitHub to reach the ApplicationSet service inside the cluster (Ingress + shared secret).

Case 3: preview environments consumed all the cluster resources

Approach: Preview namespaces use ResourceQuota (written into the preview overlay; syncPolicy.managedNamespaceMetadata namespaceMetadata only adds labels / annotations to namespaces, for example for a policy engine to match), environments are created only for labeled PRs, and a nightly script cleans up podinfo-pr-* namespaces older than 7 days; put the preview applications in a dedicated AppProject that restricts the destination namespaces to podinfo-pr-* (Hour 4).

Common errors and fixes

error listing repos/PRs: GET https://api.github.com/…: 403 API rate limit exceeded

Cause: No token is configured (60 requests per hour), or the token is shared by several ApplicationSets that poll too frequently.

kubectl -n argocd logs deploy/argocd-applicationset-controller --since=30m | grep -i "rate limit"

Fix: Configure tokenRef / a GitHub App; increase requeueAfterSeconds; configure a Webhook.

401 Bad credentials / 404 Not Found (private repo)

Cause: The token expired, the repository is not authorized, or the fine-grained token lacks Pull requests read permission; a 404 on a private repo is often just insufficient permission.

Fix: Reissue the token and update the Secret: kubectl -n argocd create secret generic github-token --from-literal=token=… --dry-run=client -o yaml | kubectl apply -f - (the label must be added again, or declared in the YAML).

After enabling strict mode, the PR generator errors: the referenced Secret is not of scm-creds type (ErrorOccurred=True)

Cause: Strict mode requires the Secret to carry the argocd.argoproj.io/secret-type: scm-creds label.

Fix:kubectl -n argocd label secret github-token argocd.argoproj.io/secret-type=scm-creds.

The PR has been open for a long time, but the preview application has not appeared

Cause: Default 30-minute polling; the PR does not have all the labels labels; the Webhook was sent to the API Server instead of the ApplicationSet controller.

Fix: Check the labels; add a refresh annotation temporarily; expose the ApplicationSet controller separately, as the official docs describe /api/webhook.

Preview application ComparisonError: … unable to resolve '9c41e2a…' to a commit SHA

Cause: The PR comes from a fork, or the commit was overwritten by a force-push, so the old SHA is no longer reachable and repo-server cannot fetch that commit from the repository.

Fix: Use branchMatch / labels to limit environments to PRs from branches in the same repository; after a force-push, wait for the next generation to update head_sha.

Command-line tasks
1. List all current preview applications and the commits they deploy.
kubectl -n argocd get applications -l gitops-lab/group=preview -o custom-columns=NAME:.metadata.name,REV:.spec.source.targetRevision,BRANCH:.metadata.annotations.gitops-lab/pr-branch
2. Make podinfo-preview call the GitHub API again immediately (without waiting for polling).
kubectl -n argocd annotate appset podinfo-preview argocd.argoproj.io/application-set-refresh=true --overwrite
Scenario analysis
The security team is worried that anyone who opens a PR could run code in the cluster. How would you design admission to the preview environments?

① Create environments only for PRs with the preview label (adding labels on GitHub requires triage or higher permission); ② accept only same-repo branches (branchMatch), do not create environments for fork PRs; ③ preview applications use a dedicated AppProject, and its destinations allow only podinfo-pr-* namespaces, forbidding cluster-scoped resources; ④ hard-code the project field, with no templating; ⑤ tokenRef strict mode + a least-privilege token; ⑥ namespace quotas and NetworkPolicy isolation.

Verified teaching videos

▶
Environments Based On Pull Requests (PRs): Using Argo CD To Apply GitOps Principles On Previews — DevOps & AI Toolkit
English · building preview environments with the PR generator
▶
Argo CD: Previewing Pull Request Changes in SECONDS! - Dag Bjerre Andersen & Sergey Shevchenko — CNCF [Cloud Native Computing Foundation]
English · community conference talk: previewing PR changes

Official docs

Video storyboard (about 80 seconds)

Shot 1 · 0–20s
Visual: GitHub PR page; the developer clicks to add the preview label.
Narration: labeling a PR with preview is the same as requesting a preview environment.
Shot 2 · 20–50s
Visual: the controller uses the token to call the GitHub API and generates a podinfo-pr-7 card; the commit number on the card changes with each new push.
Narration: the Pull Request generator reads open PRs and deploys exactly the PR's latest commit by head_sha.
Shot 3 · 50–80s
Visual: the PR is closed, the card fades out, and a grey afterimage of the namespace icon remains.
Narration: after the PR closes, the application is deleted automatically; namespaces created through CreateNamespace need to be cleaned up separately.
or reach a score of ≥ 70% in the “Quiz”

Module 7 · Progressive syncs (RollingSync) and environment promotion

42:00 – 50:00 · When one change affects several applications, let dev go first, then staging, and prod last, moving on only after each group is healthy; and how versions are promoted between environments
8 minProgressive Syncs: Beta (since v3.3.0) · disabled by defaultdeletionOrder: Reverse★★★★☆
Learning objectives
  • State the status and how to enable Progressive Syncs: Beta since v3.3.0, and still must be explicitly enabled (the controller parameter --enable-progressive-syncs, an environment variable, or argocd-cmd-params-cm in the applicationsetcontroller.enable.progressive.syncs: "true").
  • Write strategy.type: RollingSync the steps (matchExpressions + maxUpdate), understanding that it will turn off auto-sync for the generated applications, use only Application health as the gate, respect sync windows; be able to use deletionOrder: Reverse.
  • Distinguish “rolling out the same change group by group” (RollingSync) from “promoting a version from one environment to the next” (a PR that changes the overlay, Kargo, Source Hydrator), and choose a promotion approach for the team.
Prerequisites: Module 3 (generated Applications carry labels), Health Status (Hour 1). Importance:★★★★☆

What: Progressive Syncs and RollingSync

By default (AllAtOnce), when an ApplicationSet changes, all the generated Applications update at the same time; if they have automatic sync enabled, they deploy simultaneously. RollingSync Grouping Applications by their label splits the applications into several steps; only one group is synced at a time, waiting for all members of the group to become Healthy Healthy before moving on to the next group.

spec:
  strategy:
    type: RollingSync
    deletionOrder: Reverse          # optional: delete in reverse step order (prod first, dev last)
    rollingSync:
      steps:
      - matchExpressions:
        - {key: env, operator: In, values: [dev]}
      - matchExpressions:
        - {key: env, operator: In, values: [staging]}
      - matchExpressions:
        - {key: env, operator: In, values: [prod]}
        maxUpdate: 1                # sync at most 1 per batch (can also be written as "25%")
  template:
    metadata:
      labels:
        env: '{{.path.basename}}'   # the step selects Applications by this label

Behavior details (from the official v3.6.1 docs)

  • Status: Beta since v3.3.0; the docs also note that this is a feature that must be “explicitly enabled”.
  • Grouping: multiple matchExpressions within one step are “AND”; In / NotIn multiple values of an expression are “OR”; when both match In and NotIn , the NotIn takes precedence.
  • Gate: all applications in each group Healthy must be Healthy before moving to the next group; maxUpdate defaults to 100%, supports an integer or a percentage (rounded down, but at least 1 when above 0%); maxUpdate: 0 means this group is not updated automatically (requires manual sync; it can be treated as a “manual approval step”).
  • Automatic sync is turned off: RollingSync forces all generated applications to turn off automatic sync; if the template sets automated a warning is printed in the controller logs; the sync is triggered by the controller setting the Application's operation field, which is equivalent to clicking Sync in the UI, so it respects sync windows, and keeps the application's syncPolicy (for example retry).
  • Applications not selected by any step do not take part in RollingSync and require manual sync.
  • External changes: RollingSync watches the OutOfSync status of applications, so changes to overlays in Git (not only changes to the ApplicationSet) also advance step by step.
  • v3.6 changes: after detecting a change, the controller first adds refresh annotations to all applications and starts advancing only after all of them have finished reconciling, to avoid deciding based on stale state; with many applications, advancement is slightly delayed.
  • Health only: the official docs state clearly that it does not directly integrate with release controllers such as Argo Rollouts; but a Rollout puts the application in Progressing during the rollout, so it works together with RollingSync naturally (Hour 6).
  • Status fields: status.applicationStatus[] records each application's step and status (Waiting / Pending / Progressing / Healthy), with the condition RolloutProgressing indicates the rollout is in progress.

Why: RollingSync addresses the “blast radius of the same change”

Changing base, changing the ApplicationSet template, or upgrading a Helm chart referenced by all environments: these changes affect all environments at the same time. RollingSync lets the change take effect in dev first and become healthy, then go to staging, and finally prod. It does not solve promotion of different versions per environment, such as “dev uses 6.17.0 while prod still uses 6.16.0”; that is a different value in the overlay, handled by the promotion process.

Environment promotion: how a version gets from dev to prod

ApproachMechanismProsCost
PR changes the overlay (default in this lesson)A person or CI opens a PR that changes the prod overlay's newTag to the value verified in stagingSimple, auditable, tool-neutral (applies equally to Flux)Manual or self-written automation; the judgment that something is “verified” lies outside the process
RollingSyncThe same change is synced group by group, dev → staging → prod, with a health gateBuilt into ApplicationSet; limits the blast radiusBeta, must be enabled; automatic sync is turned off; only health acts as a gate
Kargo (Akuity, open source, v1.12.x)Warehouse discovers new artifacts → Freight → promotion through Stages, with verification possibleDedicated promotion orchestration with an intuitive UIAdds another set of controllers and CRDs (Hour 6)
Argo CD Source Hydrator (Beta since v3.5)Renders the DRY source and commits it to environment-specific output branches / paths, then syncsAudit the “final manifests”; promotion can be based on the rendered resultsRequires enabling commit-server and write permissions; output branches are maintained by machines, not manually maintained “environment branches”
Image Updater / CI write-backNew images are written back automatically to an environment's overlayFully automatic for devprod usually still needs PR approval (Hour 6)

When: when to turn on RollingSync

An ApplicationSet generates applications for several environments / clusters, and you often change the parts they share (templates, base, chart version). If you rely on the immediacy of application-level automatic sync and selfHeal, or your main changes are “different versions per environment”, RollingSync's benefit is limited.

Common misconceptions① “RollingSync is already GA and on by default”: in v3.6.1 it is Beta and disabled by default; it must be explicitly enabled. ② “Automatic sync can still be kept when RollingSync is on”: no, generated applications have automatic sync forcibly turned off (including the effect of selfHeal). ③ “RollingSync will automatically roll back dev when prod fails”: no, it only stops advancing; rollback is done with Git revert.

RollingSync advancement and gate

Git changebase / template / chart Step 1: env In [dev]maxUpdate 100%podinfo-dev Healthyall Healthy → proceed Step 2: env In [staging]maxUpdate 100%podinfo-staging Progressingwaiting for Healthy… Step 3: env In [prod]maxUpdate 1 (one by one)podinfo-prod WaitingIf the previous step is Degraded:will never be synced status.applicationStatus: Waiting → Pending → Progressing → Healthy; the condition RolloutProgressing=True indicates the rollout is in progress
Figure 7-1: RollingSync uses only “health” as its gate; it stops on failure and does not roll back automatically

The difference between the two kinds of “promotion”

RollingSync: the same change, taking effect in batchesMemory limit in base 128Mi → 160Midev → staging → prod synced in order; proceed once healthyOnly one commit in Git Promotion: different versions in different environmentsdev 6.17.0 · staging 6.17.0 · prod 6.16.0PR changes the newTag of the prod overlay to 6.17.0Each promotion is an independent, approvable commit
Figure 7-2: the two complement each other: promotion decides “which version prod uses”, and RollingSync decides “in what order a shared change lands”

RollingSync simulator

7 applications in three groups: dev (2), staging (2), prod (3, maxUpdate adjustable). After clicking “Push change” they advance step by step; ticking “bad image” turns one staging application into Degraded, and you can observe the rollout stop. The status names match the real values of status.applicationStatus exactly.

All applications Healthy and Synced.
$ kubectl -n argocd get appset rs-demo -o jsonpath='{.status.applicationStatus}'

Enable Progressive Syncs

configs:
  params:
    applicationsetcontroller.enable.progressive.syncs: true
helm upgrade argocd argo/argo-cd --version 10.18.0 -n argocd -f ~/gitops-lab/bootstrap/argocd-values.yaml
kubectl -n argocd get cm argocd-cmd-params-cm -o jsonpath='{.data.applicationsetcontroller\.enable\.progressive\.syncs}'; echo
kubectl -n argocd rollout restart deploy/argocd-applicationset-controller
kubectl -n argocd rollout status deploy/argocd-applicationset-controller
kubectl -n argocd get deploy argocd-applicationset-controller -o yaml | grep -A3 PROGRESSIVE
true
deployment.apps/argocd-applicationset-controller restarted
deployment "argocd-applicationset-controller" successfully rolled out
        - name: ARGOCD_APPLICATIONSET_CONTROLLER_ENABLE_PROGRESSIVE_SYNCS
          valueFrom:
            configMapKeyRef:
              key: applicationsetcontroller.enable.progressive.syncs

The ApplicationSet controller Deployment in chart 10.18.0 reads configMapKeyRef this key and injects an environment variable ARGOCD_APPLICATIONSET_CONTROLLER_ENABLE_PROGRESSIVE_SYNCS; environment variables are read only when the Pod starts, so restart the controller after changing them.

Observe the rollout

CommandPurpose
kubectl -n argocd get appset NAME -o json | jq '.status.applicationStatus'each application's step / status / message
argocd appset get NAMEcondition RolloutProgressing
argocd app list -l env=prodView applications by group
argocd app sync APPManual sync maxUpdate: 0 a group, or applications not selected by any step
kubectl -n argocd logs deploy/argocd-applicationset-controller | grep -i progressiverollout logs and the warning that automatic sync was turned off

Lab 7: enable RollingSync, observe group-by-group rollout and stop on failure (about 8 minutes)

Enable Progressive Syncs: modify it as on the “Commands” page bootstrap/argocd-values.yaml,helm upgrade restart the controller, and commit the values change to gitops-lab (bootstrap files are versioned too).
Create the demo ApplicationSet (still in ~/appset-lab/, deployed to rs-* namespaces, not affecting podinfo-*)
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: rs-demo
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - list:
      elements:
      - {env: dev}
      - {env: staging}
      - {env: prod}
  strategy:
    type: RollingSync
    deletionOrder: Reverse
    rollingSync:
      steps:
      - matchExpressions:
        - {key: env, operator: In, values: [dev]}
      - matchExpressions:
        - {key: env, operator: In, values: [staging]}
      - matchExpressions:
        - {key: env, operator: In, values: [prod]}
        maxUpdate: 1
  template:
    metadata:
      name: 'rs-{{.env}}'
      labels:
        env: '{{.env}}'
      finalizers:
      - resources-finalizer.argocd.argoproj.io
    spec:
      project: default
      source:
        repoURL: https://github.com/<you>/gitops-lab.git
        targetRevision: main
        path: 'apps/podinfo/overlays/{{.env}}'
        kustomize:
          namespace: 'rs-{{.env}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: 'rs-{{.env}}'
      syncPolicy:
        syncOptions:
        - CreateNamespace=true
cd ~/appset-lab && kubectl apply -f rs-demo.yaml
watch -n2 "kubectl -n argocd get appset rs-demo -o json | jq -r '.status.applicationStatus[] | [.application,.step,.status] | @tsv'"
rs-dev	1	Healthy
rs-prod	3	Waiting
rs-staging	2	Progressing

When first created, all three applications are OutOfSync, and the controller syncs them in step order: dev becomes Healthy first, then staging, and finally prod.

Push a “bad” shared change: in the ApplicationSet template, override the image with a tag that does not exist, and observe the rollout stop at dev.
yq -i '.spec.template.spec.source.kustomize.images = ["ghcr.io/stefanprodan/podinfo:0.0.0-doesnotexist"]' rs-demo.yaml
kubectl apply -f rs-demo.yaml
sleep 60; kubectl -n argocd get appset rs-demo -o json | jq -r '.status.applicationStatus[] | [.application,.step,.status,.message] | @tsv'
kubectl -n rs-dev get pod
rs-dev	1	Progressing	Application resource became Progressing, updating status from Pending to Progressing
rs-prod	3	Waiting	Application has pending changes (spec differs), setting status to Waiting
rs-staging	2	Waiting	Application has pending changes (spec differs), setting status to Waiting
NAME                       READY   STATUS             RESTARTS   AGE
podinfo-7c9d8f6b5-x2kqp    0/1     ImagePullBackOff   0          58s
podinfo-5f6c7b9d8c-9lmvw   1/1     Running            0          6m

The new dev Pod cannot pull the image while the old Pod still serves traffic; the Deployment never becomes Healthy, and staging and prod stay Waiting. The blast radius is limited to dev. The exact message text depends on the actual version.

Fix it and observe the rollout continue: change it to the existing 6.17.0.
yq -i '.spec.template.spec.source.kustomize.images = ["ghcr.io/stefanprodan/podinfo:6.17.0"]' rs-demo.yaml
kubectl apply -f rs-demo.yaml
sleep 90; argocd app list -l 'env in (dev,staging,prod)' | grep rs-
Confirm that automatic sync is turned off, and try reverse deletion
argocd app get rs-prod | grep "Sync Policy"          # Manual (even if automated is written in the template, it is turned off)
kubectl -n argocd delete appset rs-demo              # deletionOrder: Reverse → deletes rs-prod first, rs-dev last
kubectl -n argocd get app -l env -w                  # observe the deletion order; Ctrl+C to exit
kubectl delete ns rs-dev rs-staging rs-prod --ignore-not-found
The other side of promotion: the correct way to promote prod to 6.17.0 is still to change it via PR apps/podinfo/overlays/prod/kustomization.yaml (the same steps as the Module 1 lab). In Module 8, the podinfo ApplicationSet also uses RollingSync, so after this PR is merged the sync proceeds in dev → staging → prod order (only prod has changes, so only prod is synced).

Case 1: one chart upgrade caused failures in 40 clusters at once

Problem: The platform ApplicationSet upgraded the ingress-nginx chart to a new major version; 40 clusters synced at the same time, and the new version's default configuration was incompatible. Approach: Enable RollingSync: env In [canary] → env In [nonprod] → env In [prod] (maxUpdate 10%). Limitations: Cluster applications lose automatic sync and immediate self-healing; alerts are needed to watch applications that are OutOfSync.

Case 2: use maxUpdate: 0 as a manual approval step

Approach: Following the official example: the qa group maxUpdate: 0, the rollout stops when it reaches qa; QA manually syncs and verifies in the UI, and then the prod group continues. Limitations: Approval records are in the Argo CD audit log, not in Git; when compliance requires traceability, use PR promotion or Kargo.

Case 3: the team chose Kargo instead of RollingSync

Problem: The requirement: “promote to prod only after the staging smoke test passes, and record which image and which config commit was promoted”. Approach: Kargo's Freight packages the image and the Git commit together, with verification between Stages (Hour 6). RollingSync is kept for shared changes to platform components.

Common errors and fixes

Wrote strategy: RollingSync, but all applications still synced at the same time

Cause: Progressive Syncs was not enabled, or the ConfigMap was changed but the controller was not restarted.

kubectl -n argocd get cm argocd-cmd-params-cm -o yaml | grep progressive
kubectl -n argocd exec deploy/argocd-applicationset-controller -- env | grep PROGRESSIVE

Fix: Set applicationsetcontroller.enable.progressive.syncs: "true" and rollout restart.

An application stays OutOfSync and RollingSync never syncs it

Cause: No step's matchExpressions selects it (label missing or value mismatch), or its group maxUpdate: 0.

kubectl -n argocd get app APP --show-labels
kubectl -n argocd get appset NAME -o json | jq '.status.applicationStatus[] | select(.application=="APP")'

Fix: Add the missing labels to the template, or manually argocd app sync APP.

applicationset-controller log: … has automated sync policy, which will be disabled by RollingSync (a similar warning)

Cause: The template contains syncPolicy.automated, which conflicts with RollingSync; the controller turns it off and prints a warning.

Fix: Remove automated from the template to avoid confusion.

The rollout stays at one step for a long time: status Progressing does not change

Cause: An application in the group cannot become Healthy (image pull failure, probe failure), or a sync window forbids syncing.

argocd app get APP
argocd proj windows list default

Fix: Fix the application or revert the commit; wait within the sync window or adjust the window.

After deleting the ApplicationSet it stays in Terminating

Cause:deletionOrder: Reverse When the ApplicationSet's finalizer is set, it waits for all applications to finish deleting; the resource deletion of some application is stuck (for example PVC protection or an external finalizer).

Fix: Find the stuck application: kubectl -n argocd get app -l env, and handle the finalizers on its resources.

Command-line tasks
1. Confirm that the ApplicationSet controller has Progressive Syncs enabled.
kubectl -n argocd exec deploy/argocd-applicationset-controller -- env | grep ARGOCD_APPLICATIONSET_CONTROLLER_ENABLE_PROGRESSIVE_SYNCS
2. List all applications in rs-demo that are not Healthy, together with the step they are in.
kubectl -n argocd get appset rs-demo -o json | jq -r '.status.applicationStatus[] | select(.status!="Healthy") | "\(.application) step=\(.step) \(.status)"'
Scenario analysis
The team wants: shared base changes take effect in dev first, then staging when healthy, and finally prod; and the prod image version must go through manual approval. How would you combine the tools in this lesson?

ApplicationSet (Git directory generator, env label) + RollingSync in three steps to handle the order of shared changes; image versions are written per environment in the overlays, and prod's newTag can only be changed via PR, with CODEOWNERS designating the approvers (tool-neutral; applies equally to Flux). If you need “promote only after tests pass” and visualization, introduce Kargo. Note that RollingSync turns off automatic sync, so you need alerts for applications that stay OutOfSync for a long time.

Verified teaching videos

▶
What's New in Argo CD v3.2: Progressive Sync Deletion, Title Match Filtering and More — Akuity
English · introduces the deletion order (deletionOrder) of progressive syncs and titleMatch filtering in the PR generator

Official docs and further reading

Video storyboard (about 80 seconds)

Shot 1 · 0–25s
Visual: one Git commit; three rows of application cards (dev, staging, prod) turn yellow at the same time.
Narration: by default, one shared change hits all environments at once.
Shot 2 · 25–55s
Visual: with RollingSync on, the dev row turns green first, the staging row turns green next, and the prod row turns green one by one.
Narration: RollingSync groups by label, and moves on to the next group only after the whole group is healthy.
Shot 3 · 55–80s
Visual: one staging card turns red, and the prod row stays grey, Waiting.
Narration: if any group cannot become healthy, the rollout stops; the fix is to change Git, not to wait for an automatic rollback.
or reach a score of ≥ 70% in the “Quiz”

Module 8 · Multi-application management integrated lab

50:00 – 60:00 · Migrate the three hand-written Applications podinfo-dev / staging / prod into one ApplicationSet with zero downtime, and let new environments “go live as soon as the directory is created”
10 minZero-downtime migrationInteractive troubleshooting tree★★★★★
Learning objectives
  • Understand the key migration mechanism: the ApplicationSet will adopt existing Applications with the same name (by setting the controller ownerReference); deleting an Application that has no finalizer does not affect its workloads; resource tracking IDs are based on the application name, so applications with the same name can “seamlessly claim” the original resources.
  • Complete the migration in this order: “remove the finalizers first → replace the files in one commit → verify adoption → verify the Pods were not recreated”.
  • Use the interactive troubleshooting tree to locate common ApplicationSet problems: 0 applications, duplicate names, rendering errors, applications being repeatedly reverted, and accidental deletion.
Prerequisites: Module 2 (root.yaml), Module 3 (adoption and deletion semantics), Module 4 (Git directory generator). Importance:★★★★★

What: what turns into what

Before migrationAfter migration
Gitargocd/apps/podinfo-{dev,staging,prod}.yamlargocd/appsets/podinfo.yaml (the Git directory generator scans apps/podinfo/overlays/*)
Applications in the cluster3, managed by the root root app3 with the same names, owned by the ApplicationSet podinfo (ownerReference)
WorkloadsUnchanged: the same Deployment / Service, and Pods are not recreated
Adding an environmentCreate a new overlay + a new Application fileOnly a new overlay directory is needed

Why: why migration must be done step by step

  • Risk 1: cascading deletion. The root app prunes argocd/apps/podinfo-prod.yaml the corresponding Application; if this Application carries resources-finalizer.argocd.argoproj.io, Argo CD first deletes all the resources it manages. Prod is emptied until the ApplicationSet recreates the applications and syncs them.
  • Risk 2: two controllers fighting. If you only add the ApplicationSet and keep the old files, the root app (following the Application files in Git) and the ApplicationSet (following the template) take turns rewriting the same Application.
  • Risk 3: spec differences. The spec rendered by the template differs from the original file (for example, forgetting CreateNamespace or selfHeal), so behavior changes quietly after adoption.

How: migration steps

  1. Remove the finalizers first (the real trap): the Hour 1 podinfo-dev (and the copied staging / prod) carry resources-finalizer. First commit a single “remove finalizer” change, wait for the root app to sync, and confirm that the three Applications in the cluster no longer have finalizers. If that cannot be done, use argocd app delete APP --cascade=false to perform non-cascading deletion one by one (this removes the finalizer first, and keeps the resources).
  2. Write and preview: argocd appset generate, comparing the generated spec with the existing spec one by one.
  3. One commit: delete the three Application files and add the ApplicationSet file, then push.
  4. The root app syncs: creates the ApplicationSet and prunes the three Application objects that no longer exist in Git. At the same time, the ApplicationSet adopts or recreates the same-name applications. Whichever happens first, workloads are unaffected since there is no finalizer; the tracking ID of the same-name applications matches the annotations on the resources, so they show Synced directly.
  5. Verify: ownerReference points to the ApplicationSet; the Pods' AGE has not reset to zero; all three applications are Synced / Healthy.
  6. Harden: syncPolicy.preserveResourcesOnDeletion: true; optionally enable RollingSync (Module 7).

When: when this kind of migration fits

When a group of Applications already has the same shape and differs only in a few parameters. If the environments differ greatly (different charts, different projects), keeping independent Applications is clearer, or use the List generator + templatePatch to write the differences out explicitly.

Common misconceptions① “Migration requires deleting the old applications before creating the ApplicationSet”: without a finalizer you can replace directly, and the ApplicationSet will adopt the same-name applications; deleting first and creating later instead leaves a window where nothing manages them. ② “After the ApplicationSet adopts them, workloads get redeployed”: not as long as the rendered source / destination are the same as before. ③ “preserveResourcesOnDeletion prevents Applications from being deleted”: it only ensures that a deleted Application does not cascade-delete its resources.

Before and after migration: who manages whom

Before migration root podinfo-dev (file) podinfo-staging (file) podinfo-prod (file) After migration root AppSetpodinfo podinfo-dev (owner: AppSet) podinfo-staging (owner: AppSet) podinfo-prod (owner: AppSet) Workloads (Deployment podinfo × 3 namespaces)tracking-id: podinfo-prod:apps/Deployment:podinfo-prod/podinfo Application name unchanged → tracking ID unchanged → resources are claimed directly, Pods are not recreated
Figure 8-1: migration only changes “who owns the Application”, not “which resources the Application manages”

Migration simulator: results of three approaches

Choose one migration approach and execute it step by step. The right side shows the owner of each Application and the state of the prod workloads; the terminal shows the symptoms you would observe in the cluster (examples).

Application podinfo-prod
owner: root · Synced
prod workloads
After choosing an approach, click “Next”.
$ kubectl -n podinfo-prod get pod

Verification commands used in migration

CommandPurpose
kubectl -n argocd get app -o custom-columns=NAME:.metadata.name,OWNER:.metadata.ownerReferences[0].kind,FIN:.metadata.finalizersOverview of owners and finalizers
kubectl -n podinfo-prod get pod -o custom-columns=NAME:.metadata.name,START:.status.startTimeBefore-and-after comparison, proving the Pods were not recreated
argocd appset generate F -o json | jq '.[] | select(.metadata.name=="podinfo-prod") | .spec'Rendered spec
kubectl -n argocd get app podinfo-prod -o json | jq .specExisting spec
argocd app diff rootPreview the objects the root app is about to add / delete before committing
kubectl -n argocd get app -o custom-columns=NAME:.metadata.name,OWNER:.metadata.ownerReferences[0].kind,FIN:.metadata.finalizers
NAME              OWNER            FIN
podinfo-dev       ApplicationSet   <none>
podinfo-prod      ApplicationSet   <none>
podinfo-staging   ApplicationSet   <none>
root              <none>           <none>

If there are open preview PRs from Module 6, there will also be extra podinfo-pr-N (whose owner is also the ApplicationSet). The ApplicationSets themselves (podinfo, podinfo-preview) are viewed with kubectl -n argocd get appset , and they are managed by root.

Lab 8: migrate podinfo's three environments to an ApplicationSet (about 10 minutes)

Snapshot before migration
cd ~/gitops-lab && git pull
kubectl -n argocd get app podinfo-dev podinfo-staging podinfo-prod -o custom-columns=NAME:.metadata.name,FIN:.metadata.finalizers
for e in dev staging prod; do kubectl -n podinfo-$e get pod -o custom-columns=NAME:.metadata.name,START:.status.startTime --no-headers; done | tee /tmp/before-pods.txt
NAME              FIN
podinfo-dev       [resources-finalizer.argocd.argoproj.io]
podinfo-staging   [resources-finalizer.argocd.argoproj.io]
podinfo-prod      [resources-finalizer.argocd.argoproj.io]

This is the trap: if you delete these three files now, when the root app prunes them it will cascade-delete all the workloads of the three environments.

First commit: remove only the finalizer
for e in dev staging prod; do yq -i 'del(.metadata.finalizers)' argocd/apps/podinfo-$e.yaml; done
git diff --stat
git commit -am "podinfo apps: drop resources-finalizer before ApplicationSet migration" && git push
argocd app sync root
kubectl -n argocd get app podinfo-dev podinfo-staging podinfo-prod -o custom-columns=NAME:.metadata.name,FIN:.metadata.finalizers
NAME              FIN
podinfo-dev       <none>
podinfo-staging   <none>
podinfo-prod      <none>

If an application still has a finalizer (for example, it was originally created manually with kubectl apply , last-applied does not record that field, so sync will not delete it), remove it manually: kubectl -n argocd patch app podinfo-dev --type json -p '[{"op":"remove","path":"/metadata/finalizers"}]'. An alternative is argocd app delete podinfo-dev --cascade=false: remove the finalizer first, then delete the application, keeping the resources; the ApplicationSet then recreates the same-name applications to claim the resources. Do not proceed to the next step until FIN is <none> for all of them.

Write the ApplicationSet (the spec should match the original three files)
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: podinfo
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - git:
      repoURL: https://github.com/<you>/gitops-lab.git
      revision: main
      directories:
      - path: apps/podinfo/overlays/*
  syncPolicy:
    preserveResourcesOnDeletion: true      # keep workloads when an Application is deleted
  template:
    metadata:
      name: 'podinfo-{{.path.basename}}'
      labels:
        env: '{{.path.basename}}'
        gitops-lab/group: podinfo
    spec:
      project: default
      source:
        repoURL: https://github.com/<you>/gitops-lab.git
        targetRevision: main
        path: '{{.path.path}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: 'podinfo-{{.path.basename}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
        - CreateNamespace=true
        - PruneLast=true
      # deliberately no finalizers: combined with preserveResourcesOnDeletion, deleting an application never cascades
Preview and compare the specs one by one
for e in dev staging prod; do
  echo "== podinfo-$e"
  diff <(argocd appset generate argocd/appsets/podinfo.yaml -o json | jq -S ".[] | select(.metadata.name==\"podinfo-$e\") | .spec | {project,source,destination,syncPolicy}") \
       <(kubectl -n argocd get app podinfo-$e -o json | jq -S '.spec | {project,source,destination,syncPolicy}') && echo "same"
done
== podinfo-dev
same
== podinfo-staging
same
== podinfo-prod
same

If there are differences (for example, one repoURL has a .git and the other does not), first make the template match the original file. Migration should only change the “owner”.

One commit: delete the three Application files + add the ApplicationSet
git rm argocd/apps/podinfo-dev.yaml argocd/apps/podinfo-staging.yaml argocd/apps/podinfo-prod.yaml
git add argocd/appsets/podinfo.yaml
git commit -m "migrate podinfo dev/staging/prod Applications to ApplicationSet"
git push
argocd app diff root; argocd app sync root
Verify adoption and zero downtime
sleep 20
kubectl -n argocd get app -l gitops-lab/group=podinfo -o custom-columns=NAME:.metadata.name,OWNER:.metadata.ownerReferences[0].name,SYNC:.status.sync.status,HEALTH:.status.health.status
for e in dev staging prod; do kubectl -n podinfo-$e get pod -o custom-columns=NAME:.metadata.name,START:.status.startTime --no-headers; done | diff /tmp/before-pods.txt - && echo "pods unchanged"
NAME              OWNER     SYNC     HEALTH
podinfo-dev       podinfo   Synced   Healthy
podinfo-prod      podinfo   Synced   Healthy
podinfo-staging   podinfo   Synced   Healthy
pods unchanged
“Go live as soon as the directory is created”: add the qa environment
cp -r apps/podinfo/overlays/dev apps/podinfo/overlays/qa
sed -i 's/podinfo-dev/podinfo-qa/; s/hello from dev/hello from qa/' apps/podinfo/overlays/qa/kustomization.yaml
git add apps/podinfo/overlays/qa && git commit -m "add qa environment" && git push
kubectl -n argocd annotate appset podinfo argocd.argoproj.io/application-set-refresh=true --overwrite
sleep 30; argocd app get podinfo-qa | grep -E "Sync Status|Health Status"
Sync Status:        Synced to main (b81c0de)
Health Status:      Healthy
Delete qa and observe preserveResourcesOnDeletion
git rm -r apps/podinfo/overlays/qa && git commit -m "remove qa" && git push
kubectl -n argocd annotate appset podinfo argocd.argoproj.io/application-set-refresh=true --overwrite
sleep 30; argocd app get podinfo-qa 2>&1 | head -1; kubectl -n podinfo-qa get deploy
kubectl delete ns podinfo-qa       # resources are kept; manual cleanup is needed
rpc error: code = NotFound desc = applications.argoproj.io "podinfo-qa" not found
NAME      READY   UP-TO-DATE   AVAILABLE   AGE
podinfo   1/1     1            1           2m
(Optional) Enable RollingSync for podinfo: in spec , add Module 7's strategy (steps grouped by the env label), and remove automated. Trade-off: you gain the dev → staging → prod order and the health gate, and lose automatic sync and immediate selfHeal. This lesson defaults to not enabling it, keeping the same automatic-sync behavior as Hour 1.

Case 1: batched migration of 200 hand-written Applications

Approach: Batch by team: each batch first confirms there are no finalizers, then replaces them with an ApplicationSet in one PR; CI compares argocd appset generate specs with the existing specs in the cluster and blocks the merge if they differ. During migration, automatic prune is turned off on the root app, and deletion lists are reviewed manually. Limitations: Some applications have legacy special fields (ignoreDifferences, special syncOptions); use the Git file generator to pass them as parameters, or keep them as independent Applications.

Case 2: prod was briefly emptied on migration day

Problem: The old applications carried finalizers; when the root app pruned them, prod resources were cascade-deleted, and the ApplicationSet recreated them two minutes later. Retrospective: Added “finalizers empty” to the migration checklist; always set preserveResourcesOnDeletion: true on production ApplicationSets.

Case 3: selfHeal disappeared in one environment after migration

Problem: The template omitted selfHeal, so after adoption prod no longer automatically fixed drift; it was discovered only three weeks later. Approach: Diff the specs one by one before migration (step 3 of this lab), and alert on “OutOfSync for more than N minutes” (Prometheus lesson).

Interactive troubleshooting tree: the ApplicationSet is not working as expected

Start from the symptom you observe, answer the questions step by step, and get a diagnosis and fix commands.

Quick reference of common errors

root keeps OutOfSync: the spec of Application podinfo-prod keeps being rewritten

Cause: The old Application file is still in argocd/apps/ , so the root app and the ApplicationSet both manage the same object.

Fix: Delete the old file (migration step 4).

After migration the Applications show OutOfSync, and every resource in the diff would be recreated

Cause: The generated application names differ from the original names (for example, an extra prefix was added); tracking IDs do not match, so the new applications do not recognize the old resources, and the old resources become orphans.

Fix: Keep the name template consistent with the original names; if this has already happened, correct the names and let the new applications claim the resources, or clean up the orphaned resources.

Command-line tasks
1. Use one command to confirm that all podinfo-* applications are owned by the ApplicationSet podinfo.
kubectl -n argocd get app -l gitops-lab/group=podinfo -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.metadata.ownerReferences[0].kind}/{.metadata.ownerReferences[0].name}{"\n"}{end}'
2. Before migration, list all podinfo applications that have cascading finalizers and remove the finalizers.
for a in $(kubectl -n argocd get app -o json | jq -r '.items[] | select(.metadata.name|startswith("podinfo-")) | select((.metadata.finalizers // []) | length > 0) | .metadata.name'); do
  kubectl -n argocd patch app $a --type json -p '[{"op":"remove","path":"/metadata/finalizers"}]'
done
Scenario analysis
One week after migration, someone accidentally created a overlays/tmp-test directory under overlays and merged it, and Argo CD created the podinfo-tmp-test application. How do you prevent this?

① CODEOWNERS protection on apps/podinfo/overlays/; ② change the Git directory generator to an explicit list, or add exclude rules (for example overlays/tmp-*); ③ switch to the List generator and list the environments explicitly; ④ restrict the AppProject's destination namespaces to the known podinfo-dev/staging/prod (Hour 4), so applications targeting unknown namespaces raise InvalidSpecError and are not deployed.

Verified teaching videos

▶
ArgoCD deployment patterns: App of Apps Vs. ApplicationSets — AI Security Labs
English · comparison of the two patterns (community channel; conclusions follow this lesson's verification)
▶
Multi-cluster, multi-apps, multi-value deployments using Argo CD Application Sets - Kostis Kapelonis — CNCF [Cloud Native Computing Foundation]
English · practice of evolving from hand-written applications to an ApplicationSet

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–25s
Visual: three separate Application files next to one ApplicationSet file, with an arrow for “one commit” in between.
Narration: the core of migration is one commit: delete the three files and add one ApplicationSet.
Shot 2 · 25–60s
Visual: the owner label on the Application cards changes from root to podinfo; the timer on the Pods below keeps running without resetting to zero.
Narration: the ApplicationSet adopts the same-name applications; the resource tracking identifiers do not change, so the workloads are not recreated.
Shot 3 · 60–90s
Visual: when the red finalizer icon appears, all the Pods disappear and are then recreated.
Narration: the only trap is the finalizer: before migrating, confirm that the old applications have no cascading-delete finalizer.
or reach a score of ≥ 70% in the “Quiz”

Command cheat sheet

Argo CD v3.6 · App of Apps · ApplicationSet · every code block can be copied with one click
After-class reference

Repo layout and environment comparison (tool-neutral)

diff -ru apps/podinfo/overlays/staging apps/podinfo/overlays/prod
diff <(kubectl kustomize apps/podinfo/overlays/staging) <(kubectl kustomize apps/podinfo/overlays/prod)
grep -H newTag apps/podinfo/overlays/*/kustomization.yaml
git log --format='%h %an %s' -- apps/podinfo/overlays/prod
# Flux comparison (reference): flux bootstrap github --owner=<you> --repository=gitops-lab --path=clusters/lab

App of Apps

kubectl apply -n argocd -f argocd/root.yaml     # the only manual step
argocd app get root
argocd app diff root                             # preview the Applications to be added / deleted
argocd app delete APP --cascade=false            # delete only the Application, keep the resources
kubectl -n argocd get app -o custom-columns=NAME:.metadata.name,FIN:.metadata.finalizers
# directory: { recurse: true, exclude: 'root.yaml' }

ApplicationSet basic operations

argocd appset generate FILE [-o yaml|json|wide]  # preview only, no creation
argocd appset create FILE --upsert
argocd appset list
argocd appset get NAME                            # conditions ErrorOccurred / ResourcesUpToDate
argocd appset delete NAME                         # also deletes the Applications it owns
kubectl -n argocd annotate appset NAME argocd.argoproj.io/application-set-refresh=true --overwrite
kubectl -n argocd logs deploy/argocd-applicationset-controller --since=10m

Key template points

spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  syncPolicy:
    preserveResourcesOnDeletion: true
  template:
    metadata:
      name: '{{.path.basename}}-{{.nameNormalized}}'
  templatePatch: |
    {{- if .autoSync }}
    spec:
      syncPolicy:
        automated: {prune: true, selfHeal: true}
    {{- end }}
# Deployed via Helm: '{{`{{.cluster}}`}}'

Generator parameters

list        → any key in the elements: .env .autoSync
git dirs    → .path.path .path.basename .path.basenameNormalized (index .path.segments N)
git files   → flattened fields .cluster.name + .path.* + .path.filename
clusters    → .name .nameNormalized .server .project .metadata.labels.KEY
pullRequest → .number .branch .branch_slug .head_sha .head_short_sha .labels .author
scmProvider → .organization .repository .url .branch .sha .labels
matrix      → Cartesian product of two child generators (only 2, nesting 1 level)
merge       → aligned by mergeKeys; the base takes precedence, later ones take priority, non-matching ones are discarded

Cluster and SCM credentials

argocd cluster list
kubectl -n argocd get secret -l argocd.argoproj.io/secret-type=cluster --show-labels
kubectl -n argocd label secret in-cluster gitops-lab/managed=true --overwrite
kubectl -n argocd create secret generic github-token --from-literal=token="$GH_TOKEN"
kubectl -n argocd label secret github-token argocd.argoproj.io/secret-type=scm-creds
gh label create preview && gh pr create --label preview

Progressive Syncs (Beta, must be enabled)

# bootstrap/argocd-values.yaml
configs:
  params:
    applicationsetcontroller.enable.progressive.syncs: true
    applicationsetcontroller.enable.tokenref.strict.mode: true
# ApplicationSet
strategy:
  type: RollingSync
  deletionOrder: Reverse
  rollingSync:
    steps:
    - matchExpressions: [{key: env, operator: In, values: [dev]}]
    - matchExpressions: [{key: env, operator: In, values: [prod]}]
      maxUpdate: 1      # or "25%"; 0 = manual

Observation and troubleshooting

kubectl -n argocd rollout restart deploy/argocd-applicationset-controller
kubectl -n argocd get appset NAME -o json | jq '.status.conditions'
kubectl -n argocd get appset NAME -o json | jq -r '.status.applicationStatus[] | [.application,.step,.status] | @tsv'
argocd appset generate F -o json | jq -r '.[].metadata.name' | sort | uniq -d   # duplicate names
kubectl -n argocd get app -o custom-columns=NAME:.metadata.name,OWNER:.metadata.ownerReferences[0].kind

Quick decision notes

ScenarioChoice
Environment expressionmain branch + overlays directories; avoid long-lived environment branches; use separate repos only for compliance isolation
A small number of platform components with very different shapesApp of Apps (root.yaml)
Same shape, large numberApplicationSet; managed by root argocd/appsets/
application × clusterMatrix (Git directory × Cluster), name includes both dimensions
Defaults + a few exceptionsvalues from a Merge or Cluster generator
PR previewPull Request generator + label gate + least-privilege token + strict mode
Shared changes land in orderRollingSync (Beta, automatic sync turned off)
Promote versions per environmentPR changes the overlay; Kargo when orchestration is needed

Integrated lab + final quiz

Turn gitops-lab into a “platform repo”: root bootstraps everything, podinfo is generated by an ApplicationSet, PRs automatically get preview environments, and prod promotion goes through PR approval
After class ≈ 40 minutesIntegrates all modules
Scenario Your team plans to use gitops-lab as the official config repo. Review requirements: ① a new cluster needs only helm install + one kubectl apply to restore all applications; ② all podinfo environments are generated by one ApplicationSet, and adding an environment requires no Application to be written; ③ deleting an ApplicationSet or an environment directory does not accidentally delete workloads; ④ PRs automatically get preview environments, destroyed when closed; ⑤ version changes in prod must be an independent, approvable commit; ⑥ everything above can be proven to come from Git. Please complete this in the lab kind cluster and verify it.
Check the starting point (Modules 0, 2, 8)
cd ~/gitops-lab && git pull && tree -L 3 argocd apps
argocd app list
kubectl -n argocd get appset

You should see root, podinfo-dev/staging/prod (owned by the ApplicationSet podinfo), and the ApplicationSets podinfo and podinfo-preview. Go back to the relevant modules to fill in anything missing.

Version the bootstrap files (Modules 2, 6, 7): confirm that bootstrap/argocd-values.yaml contains Application health checks, tokenRef strict mode, optional Progressive Syncs, and has been committed.
grep -nE 'health.argoproj.io_Application|tokenref.strict|progressive.syncs' bootstrap/argocd-values.yaml
git status --short bootstrap/
Disaster recovery drill (Module 2): delete the root app (without cascading), then restore it from Git.
kubectl -n argocd delete application root     # root has no finalizer: all child objects are kept
argocd app list | grep -c podinfo              # still present
kubectl apply -n argocd -f argocd/root.yaml
sleep 20; argocd app get root | grep -E "Sync Status|Health Status"
Deletion protection verification (Modules 3, 8)
kubectl -n argocd get appset podinfo -o jsonpath='{.spec.syncPolicy.preserveResourcesOnDeletion}'; echo
kubectl -n argocd get app -l gitops-lab/group=podinfo -o custom-columns=NAME:.metadata.name,FIN:.metadata.finalizers

Expected output true and every FIN value is <none>.

PR preview + prod promotion (Modules 1, 6): open a PR that changes prod's newTag to 6.17.0, and add the preview label.
git switch -c promote-prod-6.17.0
sed -i 's/newTag: "6.16.0"/newTag: "6.17.0"/' apps/podinfo/overlays/prod/kustomization.yaml
git commit -am "promote podinfo prod to 6.17.0" && git push -u origin promote-prod-6.17.0
gh pr create --title "promote prod to 6.17.0" --body "staging verified" --label preview
diff <(git show main:apps/podinfo/overlays/prod/kustomization.yaml) apps/podinfo/overlays/prod/kustomization.yaml

The preview environment deploys the dev overlay (the design of Module 6), so the preview of this PR mainly verifies “the PR process itself”. Think about it: if you want to preview changes to the prod overlay, how should the template change? (Hint: Matrix PR generator × List generator [dev, prod], with the name including env.)

Merge and observe: approve and merge on GitHub (or gh pr merge --squash --delete-branch), then:
git switch main && git pull
sleep 60; kubectl -n podinfo-prod get deploy podinfo -o jsonpath='{.spec.template.spec.containers[0].image}'; echo
argocd app list -l gitops-lab/group=preview
ghcr.io/stefanprodan/podinfo:6.17.0
NAME  CLUSTER  NAMESPACE  PROJECT  STATUS  HEALTH  SYNCPOLICY  CONDITIONS  REPO  PATH  TARGET

After the PR is merged, the preview application is deleted; remember to clean up the podinfo-pr-N namespace.

Prove “everything comes from Git”
kubectl -n argocd get app,appset -o custom-columns=KIND:.kind,NAME:.metadata.name,OWNER:.metadata.ownerReferences[0].name,TRACK:.metadata.annotations.argocd\.argoproj\.io/tracking-id

each Application is either tracked by root (TRACK starting with root: ) or owned by the ApplicationSet; the ApplicationSets are tracked by root; only root itself is applied manually.

Retention and cleanup: the outcome of this lesson is the starting point for Hour 4 (multi-cluster will make the Matrix expand automatically to lab2),please keep. To clean up demo leftovers: kubectl -n argocd delete appset podinfo-demo rs-demo --ignore-not-found,kubectl delete ns demo-alpha demo-beta rs-dev rs-staging rs-prod --ignore-not-found. To release all resources completely: kind delete cluster --name lab (the start of the next lesson includes rebuild steps).
Acceptance checklist

Open-ended self-test (answer first on your own, then expand the reference answer)

1. Why is using long-lived branches to express environments not recommended? Does this conclusion hold for Flux?

Promotion becomes a whole-branch merge that carries unverified changes; environment-specific differences cause repeated conflicts; they cannot be compared on one screen; branches explode with environments; and it duplicates the overlay modeling. The conclusion is tool-neutral and holds for Flux too (Flux's official layout guide also divides by directory / repository).

2. When the root app is deleted, what happens to the child apps and workloads? And when a child app is pruned?

The root app has no finalizer by default: it deletes only itself, and child apps and workloads are kept. When a child app is pruned: if it carries resources-finalizer.argocd.argoproj.io then its resources are cascade-deleted; otherwise the resources become orphans and keep running.

3. Why must goTemplate be paired with missingkey=error? What problem does templatePatch solve?

By default a missing parameter is rendered as <no value>, which silently produces wrong names or paths; once enabled, it errors out directly and stops updating. Go templates can only act on string fields; templatePatch renders first and then merges, so it can generate boolean, object and list fields (such as automated and valueFiles).

4. What restrictions does Matrix have? How many outputs do Merge and Matrix each produce?

Only two child generators; one generator per element; the child generator's template is not processed; nesting only one level; consumers after producers; they cannot consume each other. Matrix = m × n; Merge = number of base generators (non-matching overrides are discarded).

5. What security issues should you watch for in PR preview environments?

Only administrators can write ApplicationSets; tokenRef strict mode and the scm-creds label; a least-privilege token or GitHub App; a label gate; the project field is not templated; fork PRs are restricted; a dedicated AppProject limits podinfo-pr-* namespaces; quotas and cleanup.

6. What is the difference between RollingSync and “environment promotion”? What is the cost of each?

RollingSync controls the same shared change the order in which it lands across groups of applications, gated on health; the cost is that it is Beta, must be enabled, and turns off automatic sync. Promotion is different environments using different versions, done by changing the overlay through PRs (or orchestrated by Kargo); the cost is that it needs process and automation. The two complement each other.

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for all technical facts in this lesson (verified on 2026-11-17)
TopicVerified conclusionSource (accessed 2026-11-17)
Argo CD versionLatest v3.6.1 (2026-11-04); concurrent patches v3.5.7, v3.4.13, v3.3.19; all docs in this lesson are taken from the v3.6.1 tagargo-cd releases
Helm chartargo-cd 10.18.0 (appVersion v3.6.1); configs.params written to argocd-cmd-params-cm; the ApplicationSet controller Deployment reads it via configMapKeyRef applicationsetcontroller.enable.progressive.syncs,…tokenref.strict.mode,…allowed.scm.providers,…enable.scm.providers,…policyargo-helm/charts/argo-cd
Progressive SyncsBeta since v3.3.0, must be explicitly enabled (--enable-progressive-syncs / environment variable / cmd-params key); RollingSync turns off automatic sync for generated applications; maxUpdate defaults to 100%, and 0 means no automatic update; deletionOrder: Reverse; since v3.6, all applications are refreshed before advancingProgressive Syncs · Upgrading 3.5→3.6
ApplicationSet status and adoptionstatus codes Waiting / Pending / Progressing / Healthy; conditions ErrorOccurred / ParametersGenerated / ResourcesUpToDate / RolloutProgressing; for an existing same-name Application the controller performs CreateOrUpdate and SetControllerReference (adoption); status.resources defaults to a cap of 5000 (since v3.2)Source code pkg/apis/application/v1alpha1/applicationset_types.go,applicationset/controllers/applicationset_controller.go (v3.6.1) · Upgrading 3.1→3.2
TemplatesgoTemplate + Sprig (except env / expandenv / getHostByName) + normalize / slugify; missingkey=error recommended but not default; templatePatch works only with goTemplate and does not support spec.project; fasttemplate will be deprecated; in Helm, escaping is requiredGo Template · Templates
GeneratorsGit polling defaults to 3 minutes (ARGOCD_APPLICATIONSET_CONTROLLER_REQUEUE_AFTER), refresh annotation argocd.argoproj.io/application-set-refresh; Cluster generator parameters and the local cluster has no Secret; Matrix's 6 restrictions; Merge override rules; PR generator polls every 30 minutes by default, GitHub fields owner/repo/tokenRef/appSecretName/labels, parameters number/branch/branch_slug/head_sha…; SCM Provider GitHub requires organizationGit · Cluster · Matrix · Merge · Pull Request · SCM Provider
SecurityOnly administrators can create / modify ApplicationSets; the risk of a templated project; tokenRef strict mode requires scm-creds label; allowed SCM list; SCM generators can be disabledSecurity · Appset in any namespace
App of AppsThe official docs recommend ApplicationSet; App of Apps is an alternative and administrators only; Application health checks were removed in 1.8 and can be restored with a Lua script in argocd-cm; since v3.2, deleting child apps from the UI behaves consistently; the finalizer controls cascading deletionCluster Bootstrapping · Resource Health
Repo layout (tool-neutral)Five reasons from Argo CD's recommendation to separate config and source repos; Flux's official layouts: Monorepo / Repo per team / Repo per app; the argument for env-per-branchArgo CD Best Practices · Flux repository structure · Codefresh
Rendered manifestsArgo CD Source Hydrator has been Beta since v3.5.0, disabled by default (commit-server + hydrator.enabled)Source Hydrator · Akuity: Rendered Manifests Pattern
Flux comparisonFlux v2.10.0 is the latest version; Flux Operator v0.62.1,ResourceSet generates resources based on an input matrix,ResourceSetInputProvider supports GitHubPullRequest, GitLabMergeRequest, etc.flux2 releases · flux-operator
Otherpodinfo 6.17.0 / 6.16.0 (2026-10-26); Kargo v1.12.6 (2026-11-16); kind v0.33.0podinfo · Kargo · kind

Video verification notes

All the following videos had their titles and channels verified via the YouTube oEmbed endpoint (2026-11-17): DevOps & AI Toolkit“GitOps: Branches, directories, or different repositories for the desired state of environments?”(c6tnnB-t470), “Environments Based On Pull Requests (PRs): Using Argo CD To Apply GitOps Principles On Previews”(cpAaI8p4R60); Akuity“Argo CD Tutorial: App of Apps in 8 Minutes”(2pvGL0zqf9o), “What's New in Argo CD v3.2: Progressive Sync Deletion, Title Match Filtering and More”(bKroKvraCNE); CNCF“Mastering ApplicationSet: Advanced Argo CD Automation - Alexander Matyushentsev, Akuity”(9RvDczVIiS0), “Manage More Clusters with Less Hassle, with Argo CD Application Sets - Jonathan West & Kshama Jain”(GcvHKc2IHi8), “Multi-cluster, multi-apps, multi-value deployments using Argo CD Application Sets - Kostis Kapelonis”(7hJvZaqiG5s), “Argo CD: Previewing Pull Request Changes in SECONDS! - Dag Bjerre Andersen & Sergey Shevchenko”(fcajag5di68); Cloud With VarJosh (FS__bq6I4m0), Chalk Talk with Amit (DysX3q2sgVo, kpX7I2si644), AI Security Labs (B1td1xRjgyk). Community-channel videos are supplementary only; specific fields and feature status follow the official docs verified in this lesson.

Voice narration notes

The “Voice” page uses the browser's Web Speech API (speechSynthesis, en-US) to read the lecture script aloud in real time; English terms are pronounced with en-US, and the result depends on the voices installed on the system. The environment that generated this course file cannot call a TTS service, so no MP3 is embedded; for offline audio, pass the lecture script to any TTS tool.

Known limitations

  • The commands in this lesson were not run one by one on a real cluster; all “expected output” is illustrative (application names, SHAs, times and message text depend on your environment and version). The ApplicationSet condition and progressive sync status messages are taken from constants in the v3.6.1 source; some log text is a free paraphrase.
  • argocd appset generate A connection to the Argo CD server is required (keep the port-forward and login active during the lab).
  • Module 6 requires a GitHub account, a fine-grained token and the gh CLI; the GitHub mode of the SCM Provider generator works per organization, and this lesson only explains it read-only. The GitHub unauthenticated REST rate limit (60 requests per hour) follows the GitHub docs.
  • This lesson declares a in-cluster cluster Secret for the Cluster / Matrix demo; in Hour 4 you register lab2 before the Matrix expands to multiple clusters.
  • Progressive Syncs is Beta: fields and behavior may change in later versions; once enabled, automatic sync of generated applications is turned off.
  • The Flux part is a conceptual comparison only (v2.10 / Flux Operator v0.62); Flux was not run in this lesson's environment.
  • The times, counts and state progressions in the animations are illustrative, used to explain the mechanism, and are not the controller's exact timing.