Hour 3: Multi-Application Management — App of Apps and ApplicationSet
- 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 thatkubectl applybootstraps the entiregitops-lab; know its permission risks, cascading deletion and Application health-check pitfalls. - Understand the ApplicationSet controller reconciliation loop: generators produce parameters →
goTemplaterender templates →templatePatchhandle 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/prodthe three hand-written Applications to one ApplicationSet with zero downtime.
One-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (kind cluster lab) |
|---|---|---|---|---|---|
| 0 | Before class | Prep: multi-environment repo layout | Check gitops-lab's overlays and add the staging / prod Application manifests | Layout self-assessment | Three overlays render successfully |
| 1 | 00–06 | Repo layout | monorepo 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 directories | Compare environment differences with diff |
| 2 | 06–13 | App of Apps and bootstrapping | root app, directory recursion, cascading deletion, Application health checks, sync waves for staged bootstrapping, permission risks | Bootstrap timeline: root app → child Applications → workloads | Write and apply argocd/root.yaml |
| 3 | 13–21 | ApplicationSet: controller and templates | controller reconciliation loop, goTemplate and missingkey=error, templatePatch, generator-level templates, sync policy and preserveResourcesOnDeletion | Parameters → template → Application renderer (editable parameters) | List generator + argocd appset generate preview |
| 4 | 21–28 | List, Git and Cluster generators | List, Git directory (exclude), Git file (JSON/YAML flattening), Cluster (label selectors, local cluster), polling and Webhook | Generator expander: input → parameter sets → Application | Git directory generator scanning overlays |
| 5 | 28–35 | Matrix and Merge | Cartesian product, parameter passing order, limits of the two child generators, Merge's mergeKeys and override order | Core animation: Git directory × cluster Matrix expansion + Merge override | Matrix (overlay × cluster) preview |
| 6 | 35–42 | SCM Provider and PR generator | discovering repos by organization, generating preview environments per PR, token permissions, polling and Webhook, strict tokenRef mode, security | PR lifecycle: label → generate → push → close → delete | Create a preview environment for a gitops-lab PR |
| 7 | 42–50 | RollingSync and environment promotion | Progressive 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 |
| 8 | 50–60 | Integrated lab | Migrate three hand-written Applications to one ApplicationSet with zero downtime; troubleshooting tree | Migration step simulation + interactive troubleshooting tree | podinfo ApplicationSet go-live |
| — | After class | Cheat sheet · Integrated lab | Platform building: root + appsets + preview environments + promotion | Final quiz (12 questions) | Integrated lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / fields | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Design a GitOps repo and environment layout (common to Argo CD / Flux) | ✓ | ✓ | · | ✓ | · | · | ✓ | ✓ | kubectl kustomize,diff | environment diff |
| App of Apps bootstrapping and cascading deletion | · | ✓ | · | · | · | · | · | ✓ | directory.recurse, finalizer | root.yaml |
| ApplicationSet templates and goTemplate | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | goTemplate,templatePatch | List preview |
| Basic generators (List / Git / Cluster) | · | · | ✓ | ✓ | ✓ | · | · | ✓ | argocd appset generate | Git directory |
| Composite generators (Matrix / Merge) | · | · | · | · | ✓ | · | · | ✓ | matrix,mergeKeys | overlay × cluster |
| PR preview environments and SCM security | · | · | · | · | · | ✓ | · | · | pullRequest.github,tokenRef | preview environments |
| Progressive syncs and environment promotion | ✓ | · | · | · | · | · | ✓ | ✓ | strategy.rollingSync | group-by-group rollout |
| Migration and troubleshooting (duplicates / conflicts / cascading deletion) | · | ✓ | ✓ | · | · | · | ✓ | ✓ | argocd appset get, controller logs | Migration drill |
Content not covered in this lesson (and where to learn it)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| Kustomize / Helm sources, multi-source Applications, sync waves details, health-check Lua | Manifests and sync control belonging to a single Application | Hour 2 |
Second cluster lab2, AppProject, RBAC, SSO, apps / appsets in any namespace | This lesson's Cluster generator only uses the local cluster and a “simulated” cluster Secret for demonstration; formal multi-cluster is covered in the next lesson | Hour 4 |
| Argo Rollouts, Image Updater, Kargo hands-on | This lesson only covers the idea of “promotion” and RollingSync | Hour 6 |
| Full use of Flux | This lesson only covers Flux's equivalents in the repo layout and comparison tables | Flux: Ways of structuring your repositories |
| How CI changes Git (PRs that update image tags) | Belongs to the CI topic | GitHub 8 hours · GitLab 8 hours |
How to use this course material
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.
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).
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.
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)
- CompletedHour 1: kind cluster
lab(contextkind-lab), namespaceargocdin which Argo CD was installed with Helm (releaseargocd, chartargo/argo-cd); locally you have~/gitops-lab, with the remote being your GitHub repogitops-lab(default branchmain). apps/podinfo/base(Deployment + Service, container namepodinfod) andapps/podinfo/overlays/dev|staging|prodalready exist; the overlay containsnamespace: podinfo-<env>, replicas 1 / 2 / 3.- installed
kubectl,helm,argocdCLI (ideally matching the server version),git, optionaljq,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.
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.
Module 1 · Repo layout: monorepo, multi-repo and environment directories
- 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.
What: the three questions a GitOps repo must answer
- Where do code and configuration live?— the same repository, or an application source repo plus a deployment config repo (config repo / environment repo).
- How are environments expressed?— directories under one branch (
overlays/dev|staging|prod), one branch per environment, or one repository per environment. - 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 for | personal projects, small teams, demos | most teams | multi-team platforms (multi-tenancy in Hour 4) |
| CI writes image tags back | easily triggers a loop; needs path filters / [skip ci] | write back to the config repo, no loop | same as left |
| Permissions | coarse: being able to merge code ≈ being able to change production | set CODEOWNERS and branch protection on the config repo separately | the platform team controls root / appsets; teams change only their own directories or repos |
| gitops-lab in this lesson | is 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
| Approach | Example | What is the promotion operation (dev → prod) | Assessment |
|---|---|---|---|
| Environment directories (recommended) | main under the branch overlays/dev,overlays/prod | In a PR, change the newTag of the prod overlay to the value verified in dev | All 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 branches | merge the dev branch into the prod branch | see the 5 problems below |
| Environment repos | gitops-prod separate repositories | cross-repo commits / PRs | used for strong permission isolation and compliance requirements; the cost is duplication and cross-repo syncing |
Why “one branch per environment” is not recommended
- 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.
- 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.
- 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 onlydiff -r overlays/staging overlays/prod. - 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.
- 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 |
| Pros | change one place and it affects all environments; fewer files | the PR shows “what will actually be applied”; not affected by differences in rendering tool versions; the clearest audit trail |
| Cons | when 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 support | Argo CD and Flux both render Kustomize and Helm natively | Argo 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”
| Requirement | Argo CD | Flux (v2.10) |
|---|---|---|
| describe “which directory goes where” | Application (source + destination) | Kustomization (sourceRef + path) or HelmRelease |
| environment differences | Kustomize 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 dependencies | Sync Waves (within one application), RollingSync (groups of applications inside an ApplicationSet) | Kustomization's dependsOn |
| multi-cluster | Centralized: 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.
Architecture diagram: recommended gitops-lab layout and how the two GitOps tools read it
Comparison diagram: promoting one image version: what changes in the branch model vs the directory model
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.
Core commands: compare environments, review promotion
| Command | Purpose | Notes |
|---|---|---|
diff -ru overlays/staging overlays/prod | Compare the “source of differences” between two environments | In the directory model, the next command shows all differences |
diff <(kubectl kustomize A) <(kubectl kustomize B) | Compare rendered results | Mandatory when changing base; may differ from Argo CD's rendering due to kustomize version differences |
git log --oneline -- apps/podinfo/overlays/prod | Change history of prod | Audit “who changed prod, and when” |
argocd app diff podinfo-prod --local … | Compare local files with the cluster | Preview the impact before committing (login required) |
flux bootstrap github … | Flux comparison: initialize the Kustomization tree | For 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)
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”.
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.
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
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.
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.
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
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
Official docs and further reading
- Argo CD Best Practices: Separating Config Vs. Source Code Repositories
- Flux: Ways of structuring your repositories (Monorepo / Repo per team / Repo per app)
- Codefresh: Stop Using Branches for Deploying to Different GitOps Environments
- Akuity: The Rendered Manifests Pattern · Argo CD Source Hydrator
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.
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.
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.
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.
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.
Module 2 · App of Apps pattern and bootstrapping
- 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.
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 point | Notes |
|---|---|
| Directory-type source | argocd/ 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 finalizer | Deleting the root app removes only itself; child Applications keep existing (becoming orphans). This is the safe default. |
| Finalizer on child apps | If 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 status | Argo 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 bootstrapping | Add 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 Apps | ApplicationSet (Modules 3–8) | |
|---|---|---|
| Source of child apps | Hand-written Application files | Generated automatically by generators + templates |
| Suitable for | a 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) |
| Readability | each application is clear at a glance | you must understand the generators to know what will be generated (argocd appset generate preview) |
| Common combination | the 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. | |
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).Structure diagram: root app → child Applications → workloads
Deletion semantics: whoever carries the finalizer cascades
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.
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
kubectl apply -n argocd -f argocd/root.yaml | Bootstrap the root app | The 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-operation | Check which Applications the root app manages | In the resource list, Kind is Application |
argocd app list -o name | List all applications | v3 tracks resources with annotations by default, with no app.kubernetes.io/instance Filterable by label |
argocd app delete APP --cascade=false | Delete only the Application, keep the resources | Used for migration and adoption |
argocd app set root --directory-recurse | Enable directory recursion from the command line | For 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)
<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 pushkubectl 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
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
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)
argocd app diff root will show the objects about to be deleted.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.
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'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
Official docs
- Cluster Bootstrapping (App of Apps)
- Resource Health: Argo CD App
- App Deletion (finalizers and cascading deletion)
- Directory (recurse / include / exclude)
Video storyboard (about 75 seconds)
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.
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.
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.
Module 3 · ApplicationSet: controller and templates
- Draw the reconciliation loop of the ApplicationSet controller: generate parameters → render template → apply templatePatch → create / update / delete Applications → write status conditions.
- Always use
goTemplate: trueandgoTemplateOptions: ["missingkey=error"]; be able to use Sprig,normalize,slugify; know that Go templates only act on string fields, while boolean / object fields must usetemplatePatch. - Master the Application modification policies (
sync/create-only/create-update/create-delete),preserveResourcesOnDeletion,ignoreApplicationDifferences, and useargocd appset generateto preview before creating.
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.yamlthree 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
- Triggers: ApplicationSet changes, changes to the Applications it owns, cluster Secret changes, Git polling (default 3 minutes,
requeueAfterSecondsadjustable per ApplicationSet), SCM/PR polling (default 30 minutes), or an ApplicationSet Webhook. - 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. - Render: render
spec.templatefor each parameter set (if the generator itself hastemplate, it is merged with the outer template first, with the generator's fields taking precedence); then the renderedtemplatePatchis applied as a patch. - Validate: check that the name is valid and the target cluster and project exist; duplicate Applications with the same name raise an error.
- 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.
- Write status:
status.conditionsinErrorOccurred,ParametersGenerated,ResourcesUpToDate,RolloutProgressing(progressive syncs, Module 7), andstatus.resources(up to 5000 entries by default since v3.2).
Template engines: fasttemplate vs Go template
Default (fasttemplate,{{name}}) | goTemplate: true ({{.name}}, recommended) | |
|---|---|---|
| Syntax | Simple string substitution; nested parameters are written as {{path.basename}} | Go text/template + Sprig (except env,expandenv,getHostByName) + normalize,slugify |
| Conditionals / loops | not supported | supported (but only inside a single string field) |
| Missing parameters | kept as-is | default output <no value>; with missingkey=error set, it errors out directly (strongly recommended) |
| templatePatch | not available | available |
| Status | the official docs say it will be deprecated | New 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
| Setting | Meaning |
|---|---|
--policy / applicationsetcontroller.policy | Controller level: sync (default, does create, update and delete),create-only,create-update,create-delete |
spec.syncPolicy.applicationsSync | the policy of a single ApplicationSet; requires the controller to enable applicationsetcontroller.enable.policy.override, and the controller-level --policy takes precedence |
spec.syncPolicy.preserveResourcesOnDeletion: true | ApplicationSet deletion does not cascade-delete the Application's resources (recommended for production) |
spec.ignoreApplicationDifferences | lets users manually change certain fields on the generated Application (such as temporarily disabling auto-sync) without them being reverted |
spec.preservedFields | keeps 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.
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
Template merge order
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).
podinfo-{{.env}} · path = apps/podinfo/overlays/{{.env}} · templatePatch: {{- if .autoSync}} add automatedCore commands and parameters
| Command | Purpose | Notes |
|---|---|---|
argocd appset generate FILE | Render 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 ApplicationSet | In GitOps scenarios, usually commit it to argocd/appsets/ and let root sync it |
argocd appset get NAME | Check conditions and generated apps | First stop for troubleshooting |
argocd appset list / delete | List / delete | Deleting also deletes the Applications it owns |
kubectl -n argocd get applicationsets | Same as above (short name appsets) | |
kubectl -n argocd logs deploy/argocd-applicationset-controller | Controller logs | Render errors, permission errors and SCM rate limiting all show up here |
kubectl -n argocd annotate appset NAME argocd.argoproj.io/application-set-refresh=true | Refresh 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.
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.
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.
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.
'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.
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-foundCase 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 .
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"
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
Official docs
- ApplicationSet overview
- Templates (including templatePatch)
- Go Template
- Controlling Resource Modification
- ApplicationSet Security
Video storyboard (about 90 seconds)
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.
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.
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.
Module 4 · Generators: List, Git directory / file and Cluster
- 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.
What: the four basic generators
| Generator | Input | Parameters produced (goTemplate syntax) | Typical use |
|---|---|---|---|
| List | elements 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 objects | A small, fixed number of environments; combined with Matrix |
| Git directory | repoURL + revision + directories[].path (glob; can use exclude: true exclude) | .path.path,.path.basename,.path.basenameNormalized,index .path.segments n; optional values → .values.x | automatic discovery of “one directory = one application / environment” |
| Git file | files[].path (glob, such as cluster-config/**/config.json) | fields of the file content flattened (cluster.name) + .path.* + .path.filename | one config file per environment / cluster, used when there are more fields than the directory name |
| Cluster | clusters 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 newqa/directory, and it appears automatically after committingpodinfo-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.basenameis always the rightmost directory name:apps/podinfo/overlays/dev→dev;index .path.segments 1→podinfo.excludethe rule applies to alldirectoriesentries; any matching directory is always excluded.- When two Git generators are used in the same Matrix, use
pathParamPrefixto distinguish parameter names, otherwise.pathwill 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.
valuesfields can append fixed parameters to every cluster; when referencing them, add the prefix.values.;flatList: truecan 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
| Mechanism | Delay | Notes |
|---|---|---|
| Default polling | 3 minutes | set globally by ARGOCD_APPLICATIONSET_CONTROLLER_REQUEUE_AFTER ; a single ApplicationSet uses requeueAfterSeconds |
| repo-server revision cache | may be longer | The 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 annotation | immediately | argocd.argoproj.io/application-set-refresh (any value); bypasses the revision cache and is removed automatically after processing |
| ApplicationSet Webhook | within seconds | Webhook 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 |
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
Why the local cluster is excluded by the label selector
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.
Core commands
| Command | Purpose | Notes |
|---|---|---|
argocd cluster list | List the clusters visible to the Cluster generator | the local cluster appears as in-cluster |
kubectl -n argocd get secret -l argocd.argoproj.io/secret-type=cluster --show-labels | View cluster Secrets and labels | These are the Secrets the Cluster generator selects |
kubectl -n argocd label secret S key=value | Label a cluster | A label change triggers the ApplicationSet to regenerate |
argocd appset generate FILE -o yaml | Preview the generated result | |
kubectl -n argocd annotate appset NAME argocd.argoproj.io/application-set-refresh=true | Refresh immediately after a new Git commit | No 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)
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.
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.
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.
~/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.
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/*/
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
Official docs
Video storyboard (about 80 seconds)
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?
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.
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.
Module 5 · Composite generators: Matrix and Merge
- 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
templateis 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
mergeKeysto 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.
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)
- 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).
- 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). - The
templateon child generators is not processed. - Composite generators (matrix / merge) can be nested only once; a third level has no effect.
- Parameter consumers must come after producers.
- 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}
| Matrix | Merge | |
|---|---|---|
| Count | m × n | = number of base generators |
| Parameter merge | union of each pair (a, b) | override after matching by mergeKeys |
| Number of child generators | 2 | 2 or more |
| Typical scenario | applications × clusters, environments × regions | defaults + 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.
Matrix: 3 directories × 2 clusters = 6 Applications
Merge: base + overrides, aligned by mergeKeys
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.
Core commands: predict and verify combined results
| Command | Purpose | Notes |
|---|---|---|
argocd appset generate F -o json | jq length | Number of results | should equal m × n (Matrix) or the number of base sets (Merge) |
argocd appset generate F -o json | jq -r '.[].metadata.name' | sort | uniq -d | Find duplicate names | Any output will report duplicate name |
argocd appset get NAME | Check the ErrorOccurred condition | Composition 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)
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.
'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{{.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.)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.
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
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
Official docs
- Matrix Generator (including Restrictions)
- Merge Generator
- Cluster Bootstrapping (Matrix + cluster label example)
Video storyboard (about 90 seconds)
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.
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.
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.
Module 6 · SCM Provider and Pull Request generator: preview environments
- 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
previewlabel →podinfo-pr-<number>application that deploys the PR'shead_sha, which is deleted automatically after the PR closes. - Configure the GitHub token correctly (fine-grained, read-only, minimal repository scope),
tokenRefstrict mode, allowed SCM addresses, and understand polling and the ApplicationSet Webhook.
What: two generators that “read the SCM API”
| SCM Provider generator | Pull Request generator | |
|---|---|---|
| What they discover | in an organization / group,repositories (can scan all branches) | in a repository,open PRs / MRs |
| Supported platforms | GitHub, GitLab, Gitea, Bitbucket Server / Cloud, Azure DevOps, AWS CodeCommit (Alpha) | GitHub, GitLab, Gitea, Bitbucket Server / Cloud, Azure DevOps |
| Required GitHub fields | organization (organization name; use multiple generators for multiple organizations) | owner (organization or user),repo |
| filters | filters: repositoryMatch,pathsExist,pathsDoNotExist,labelMatch (GitHub uses repository topics),branchMatch | GitHub / 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 use | An organization with “one repo per microservice”; when a repo contains a deploy/ directory, it is deployed automatically | Create 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
- 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. - Filtered by
labelsandfilters, each PR produces one set of parameters. - The template usually uses
targetRevision: '{{.head_sha}}'to deploy the PR's latest commit exactly, with the name and namespace carrying{{.number}}. - 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
tokenRefOptional: 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 onlygitops-labone 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)
| Key | Purpose |
|---|---|
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.providers | Whitelist 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. |
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.
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
SCM Provider: organization → repository → application
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).
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl -n argocd create secret generic github-token --from-literal=token=… | Save the token | then add the label argocd.argoproj.io/secret-type=scm-creds (needed in strict mode) |
gh label create preview | Create the label in the repo | GitHub CLI |
gh pr create --label preview … | Create a PR with the label | |
gh pr close N --delete-branch | Close the PR | The preview application is deleted afterwards |
curl -H "Authorization: Bearer $T" https://api.github.com/rate_limit | Check the remaining token quota | Troubleshoot 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)
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
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
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
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
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.
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
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}argocd/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.
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
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
Official docs
- Pull Request Generator
- SCM Provider Generator
- ApplicationSet in any namespace (tokenRef strict mode, allowed SCM)
- GitHub REST API rate limits
Video storyboard (about 80 seconds)
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.
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.
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.
Module 7 · Progressive syncs (RollingSync) and environment promotion
- 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, orargocd-cmd-params-cmin theapplicationsetcontroller.enable.progressive.syncs: "true"). - Write
strategy.type: RollingSyncthe 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 usedeletionOrder: 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.
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
matchExpressionswithin one step are “AND”;In/NotInmultiple values of an expression are “OR”; when both matchInandNotIn, theNotIntakes precedence. - Gate: all applications in each group Healthy must be Healthy before moving to the next group;
maxUpdatedefaults to 100%, supports an integer or a percentage (rounded down, but at least 1 when above 0%);maxUpdate: 0means 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
automateda warning is printed in the controller logs; the sync is triggered by the controller setting the Application'soperationfield, 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'sstepandstatus(Waiting/Pending/Progressing/Healthy), with the conditionRolloutProgressingindicates 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
| Approach | Mechanism | Pros | Cost |
|---|---|---|---|
| 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 staging | Simple, auditable, tool-neutral (applies equally to Flux) | Manual or self-written automation; the judgment that something is “verified” lies outside the process |
| RollingSync | The same change is synced group by group, dev → staging → prod, with a health gate | Built into ApplicationSet; limits the blast radius | Beta, 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 possible | Dedicated promotion orchestration with an intuitive UI | Adds 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 syncs | Audit the “final manifests”; promotion can be based on the rendered results | Requires enabling commit-server and write permissions; output branches are maintained by machines, not manually maintained “environment branches” |
| Image Updater / CI write-back | New images are written back automatically to an environment's overlay | Fully automatic for dev | prod 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.
RollingSync advancement and gate
The difference between the two kinds of “promotion”
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.
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
| Command | Purpose |
|---|---|
kubectl -n argocd get appset NAME -o json | jq '.status.applicationStatus' | each application's step / status / message |
argocd appset get NAME | condition RolloutProgressing |
argocd app list -l env=prod | View applications by group |
argocd app sync APP | Manual sync maxUpdate: 0 a group, or applications not selected by any step |
kubectl -n argocd logs deploy/argocd-applicationset-controller | grep -i progressive | rollout 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)
bootstrap/argocd-values.yaml,helm upgrade restart the controller, and commit the values change to gitops-lab (bootstrap files are versioned too).~/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.
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.
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-
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
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.
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)"'
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
Official docs and further reading
- Progressive Syncs
- Upgrading 3.5 → 3.6 (changes to the Progressive Sync refresh annotation)
- Source Hydrator
- Kargo docs
Video storyboard (about 80 seconds)
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.
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.
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.
Module 8 · Multi-application management integrated lab
- 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.
What: what turns into what
| Before migration | After migration | |
|---|---|---|
| Git | argocd/apps/podinfo-{dev,staging,prod}.yaml | argocd/appsets/podinfo.yaml (the Git directory generator scans apps/podinfo/overlays/*) |
| Applications in the cluster | 3, managed by the root root app | 3 with the same names, owned by the ApplicationSet podinfo (ownerReference) |
| Workloads | Unchanged: the same Deployment / Service, and Pods are not recreated | |
| Adding an environment | Create a new overlay + a new Application file | Only 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.yamlthe corresponding Application; if this Application carriesresources-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
CreateNamespaceorselfHeal), so behavior changes quietly after adoption.
How: migration steps
- 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, useargocd app delete APP --cascade=falseto perform non-cascading deletion one by one (this removes the finalizer first, and keeps the resources). - Write and preview:
argocd appset generate, comparing the generated spec with the existing spec one by one. - One commit: delete the three Application files and add the ApplicationSet file, then push.
- 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.
- Verify: ownerReference points to the ApplicationSet; the Pods' AGE has not reset to zero; all three applications are Synced / Healthy.
- 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.
Before and after migration: who manages whom
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).
Verification commands used in migration
| Command | Purpose |
|---|---|
kubectl -n argocd get app -o custom-columns=NAME:.metadata.name,OWNER:.metadata.ownerReferences[0].kind,FIN:.metadata.finalizers | Overview of owners and finalizers |
kubectl -n podinfo-prod get pod -o custom-columns=NAME:.metadata.name,START:.status.startTime | Before-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 .spec | Existing spec |
argocd app diff root | Preview 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)
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.
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.
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 cascadesfor 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”.
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
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
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
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
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.
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"}]'
doneOne 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
Official docs
Video storyboard (about 90 seconds)
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.
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.
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.
Command cheat sheet
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 = manualObservation 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
| Scenario | Choice |
|---|---|
| Environment expression | main branch + overlays directories; avoid long-lived environment branches; use separate repos only for compliance isolation |
| A small number of platform components with very different shapes | App of Apps (root.yaml) |
| Same shape, large number | ApplicationSet; managed by root argocd/appsets/ |
| application × cluster | Matrix (Git directory × Cluster), name includes both dimensions |
| Defaults + a few exceptions | values from a Merge or Cluster generator |
| PR preview | Pull Request generator + label gate + least-privilege token + strict mode |
| Shared changes land in order | RollingSync (Beta, automatic sync turned off) |
| Promote versions per environment | PR changes the overlay; Kargo when orchestration is needed |
Integrated lab + final quiz
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.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.
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/
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"
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>.
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.)
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.
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.
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).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
| Topic | Verified conclusion | Source (accessed 2026-11-17) |
|---|---|---|
| Argo CD version | Latest 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 tag | argo-cd releases |
| Helm chart | argo-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,…policy | argo-helm/charts/argo-cd |
| Progressive Syncs | Beta 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 advancing | Progressive Syncs · Upgrading 3.5→3.6 |
| ApplicationSet status and adoption | status 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 |
| Templates | goTemplate + 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 required | Go Template · Templates |
| Generators | Git 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 organization | Git · Cluster · Matrix · Merge · Pull Request · SCM Provider |
| Security | Only 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 disabled | Security · Appset in any namespace |
| App of Apps | The 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 deletion | Cluster 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-branch | Argo CD Best Practices · Flux repository structure · Codefresh |
| Rendered manifests | Argo CD Source Hydrator has been Beta since v3.5.0, disabled by default (commit-server + hydrator.enabled) | Source Hydrator · Akuity: Rendered Manifests Pattern |
| Flux comparison | Flux 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 |
| Other | podinfo 6.17.0 / 6.16.0 (2026-10-26); Kargo v1.12.6 (2026-11-16); kind v0.33.0 | podinfo · 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 generateA 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-clustercluster Secret for the Cluster / Matrix demo; in Hour 4 you registerlab2before 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.