Education › OSS Deep Dives › Stage 1: GitOps & platform engineering

Argo CD, from the inside

The repo server, application controller and API server; ApplicationSets, sync waves, hooks, projects and running Argo CD at scale.

Intermediate ~35 min read Module 1 of 10

The DevOps track showed you the GitOps idea and a first Argo CD Application. This lesson opens the argoproj/argo-cd repository itself: which process does what, how a sync is ordered, how one ApplicationSet replaces fifty hand-written Applications, how projects fence teams in, and which knobs matter when Argo CD manages hundreds of apps across many clusters.

After this module you can
  • Name the Argo CD components and say which one to look at when a sync is slow, wrong or failing
  • Order a deployment with sync waves and PreSync, PostSync and SyncFail hooks
  • Generate Applications per directory or per cluster with an ApplicationSet
  • Restrict a team to its repositories, clusters and resource kinds with an AppProject
  • Tune and shard the application controller for large installations

Inside the repository: one binary, several jobs

Argo CD is written in Go and ships as one container image whose entrypoint decides which component to run. The top-level folders of the repository map almost one-to-one onto the processes you see in the argocd namespace, which makes the code a useful map when you debug.

FolderRuns asJob
server/argocd-servergRPC/REST API behind the UI and CLI: auth, RBAC, sync and rollback requests, Git webhooks
reposerver/argocd-repo-serverClones Git (or pulls Helm and OCI charts), caches them, and renders plain manifests
controller/argocd-application-controllerCompares live state with rendered desired state, sets sync and health status, runs syncs
applicationset/argocd-applicationset-controllerTurns one ApplicationSet into many Applications using generators
notification_controller/argocd-notifications-controllerSends Slack, email or webhook messages on triggers such as sync failed
commitserver/argocd-commit-serverOptional: writes rendered manifests back to Git for the source hydrator
fetchrenderwatch, applyApplicationsrequestsstatus, syncGit / Helm repodesired stateRepo serverclone, renderApp controllerdiff, sync, healthTarget clusterlive stateApplicationSetgenerates appsUI, CLI, CIAPI serverauth, RBAC, webhooks
The repo server turns Git into manifests, the application controller diffs them against the cluster and syncs, and the API server is only the front door for people and CI.

Two more pieces complete the picture: Redis, a cache the controller and API server share (it holds no state you cannot rebuild), and Dex, an optional identity broker for SSO. The gitops-engine/ folder holds the reusable diff-and-sync library that the controller is built on, and resource_customizations/ holds the Lua health checks that teach Argo CD when a custom resource counts as Healthy.

Tip

Debug by component. Manifests look wrong or a Helm value is ignored: read the repo server logs. Status stuck at Unknown or syncs queue up: the application controller. Login, RBAC or webhook problems: the API server.

How a sync is ordered: phases, waves and hooks

A sync is not one big kubectl apply. Argo CD runs it in phases — PreSync, Sync, PostSync, plus SyncFail if something breaks — and inside each phase it applies resources in waves. A wave is the integer in the argocd.argoproj.io/sync-wave annotation. Everything defaults to wave 0, waves can be negative, and Argo CD applies the lowest wave first and waits for it to be healthy before moving on.

A hook is any resource carrying the argocd.argoproj.io/hook annotation, usually a Job. A PreSync hook that fails stops the sync before your Deployment is touched, which makes it the right place for a database migration or a pre-flight check. PostSync hooks run only after every resource is Healthy, so they suit smoke tests and notifications.

A migration Job that must finish before the new pods roll out
yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: db-migrate
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: ghcr.io/example/orders:1.8.0
          command: ["./manage", "migrate"]
  • Put a Namespace, CRDs or a Secret in wave -1 so they exist before the workloads in wave 0 that need them.
  • When pruning, the order is reversed: higher waves are deleted first.
  • Hooks do not run during a selective sync (syncing only some resources from the UI).

ApplicationSets: stop copying Applications

Once you have a dozen services or clusters, hand-writing one Application each turns into copy-paste drift. An ApplicationSet pairs a generator, which produces a list of parameter sets, with a template that becomes one Application per parameter set. The generators in the docs include List, Cluster, Git (directories or files), Matrix and Merge (combine two generators), Pull Request, SCM Provider, Cluster Decision Resource and Plugin.

One Application per folder under addons/: add a folder, get an app
yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: cluster-addons
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    - git:
        repoURL: https://github.com/example/platform.git
        revision: HEAD
        directories:
          - path: addons/*
  template:
    metadata:
      name: '{{.path.basename}}'
    spec:
      project: platform
      source:
        repoURL: https://github.com/example/platform.git
        targetRevision: HEAD
        path: '{{.path.path}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: '{{.path.basename}}'
      syncPolicy:
        syncOptions:
          - CreateNamespace=true

The Cluster generator is the multi-cluster workhorse: it emits one parameter set per cluster registered in Argo CD, optionally filtered by label, so env=prod clusters get the production overlay automatically. Matrix a Cluster generator with a Git generator and you get every add-on on every matching cluster from about thirty lines of YAML.

Watch out

Deleting an ApplicationSet deletes the Applications it generated, and with the resources finalizer those delete their workloads too. Review ApplicationSet changes as carefully as you would a production deploy.

AppProjects: guard rails per team

Every Application belongs to an AppProject, and the default project allows everything. For anything shared, create one project per team that says which repositories it may deploy from, which cluster and namespace pairs it may deploy to, and which resource kinds it may create. A team that cannot create a ClusterRole through Argo CD cannot escalate its own permissions through Git either.

The payments team may deploy its own repos into payments-* namespaces only
yaml
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: payments
  namespace: argocd
spec:
  sourceRepos:
    - https://github.com/example/payments-*
  destinations:
    - server: https://kubernetes.default.svc
      namespace: payments-*
  clusterResourceWhitelist: []
  namespaceResourceBlacklist:
    - group: ''
      kind: ResourceQuota

An empty clusterResourceWhitelist means no cluster-scoped resources at all. Projects also carry roles whose JWT tokens let a CI job trigger syncs for that project only, and sync windows that block automatic syncs during, say, a quarter-end freeze.

Running Argo CD at scale

By default the controller re-checks Git for every Application about every three minutes (timeout.reconciliation in the argocd-cm ConfigMap) and handles work with 20 status processors and 10 operation processors. The high-availability guide suggests about 50 and 25 for roughly a thousand applications. Configure Git webhooks so a push triggers a refresh at once instead of waiting for the next poll.

  • Shard the controller when it manages many clusters: raise the replica count of argocd-application-controller and set ARGOCD_CONTROLLER_REPLICAS to the same number; clusters are spread across replicas.
  • Scale the repo server horizontally when rendering is the bottleneck, which is common with large Helm charts or many Kustomize overlays.
  • Use the HA manifests (Redis with Sentinel, multiple API servers) for production, and pin a released version instead of tracking stable.
  • Install with kubectl apply --server-side: some CRDs, such as ApplicationSet, exceed the annotation size limit of client-side apply.

Newer releases add the source hydrator (beta since v3.5): instead of rendering Helm or Kustomize in memory, Argo CD renders once, commits the plain manifests to a branch, and syncs from there, so every change to what actually runs is a reviewable diff. It is disabled by default and needs the commit server.

Hands-on practice

Waves, hooks and an ApplicationSet on a laptop cluster

  1. Create a local cluster with kind or k3d, then install Argo CD with kubectl create namespace argocd and kubectl apply -n argocd --server-side --force-conflicts -f pointing at the install.yaml of a pinned release.
  2. Run kubectl get pods -n argocd and match each pod to a folder in the table above.
  3. In a Git repo of your own, create addons/nginx and addons/redis folders with a simple Deployment in each, then apply the ApplicationSet from this lesson pointing at your repo.
  4. Run argocd app list and confirm two Applications appeared; add an addons/echo folder, push, and watch a third one appear.
  5. Add a PreSync Job that runs sleep 20 and a ConfigMap annotated with sync-wave -1, sync, and watch the order in the UI's sync status panel.
  6. Make the Job fail (exit 1) and confirm the Deployment is not updated.
  7. Delete the ApplicationSet in a throwaway cluster and observe what happens to the generated Applications.
Cheat sheet

Argo CD, from the inside — at a glance

Main things to focus on

  • Repo server renders manifests; application controller diffs and syncs; API server serves the UI, CLI and webhooks.
  • Sync order is phase (PreSync, Sync, PostSync) then wave (lowest integer first, default 0).
  • A failed PreSync hook stops the sync before workloads change: put migrations and checks there.
  • ApplicationSet = generator (list of parameters) + template (one Application each).
  • Never leave teams on the default project; restrict repos, destinations and kinds with an AppProject.
  • Scale by sharding the controller across clusters and adding repo server replicas.

CLI

argocd admin initial-password -n argocdPrint the generated admin password
argocd app listAll Applications with sync and health status
argocd app diff APPShow what a sync would change
argocd app sync APP --pruneSync now and delete resources removed from Git
argocd app history APPPast syncs and their revisions
argocd app rollback APP IDRoll back to a history entry (auto-sync must be off)
argocd cluster add CONTEXTRegister another cluster from your kubeconfig

Annotations

argocd.argoproj.io/sync-wave: "-1"Apply this resource before wave 0
argocd.argoproj.io/hook: PreSyncRun before the main sync (also Sync, PostSync, SyncFail, Skip)
argocd.argoproj.io/hook-delete-policy: BeforeHookCreationDelete the previous hook before creating the new one
argocd.argoproj.io/sync-options: Prune=falseNever prune this resource

Application syncPolicy

automated: {prune: true, selfHeal: true}Auto-sync, delete removed resources, revert manual drift
syncOptions: [CreateNamespace=true]Create the destination namespace if missing
syncOptions: [ServerSideApply=true]Use server-side apply for large or shared objects
ignoreDifferences: jsonPointers: [/spec/replicas]Ignore fields another controller owns, such as HPA replicas

Scale and config

timeout.reconciliation: 180sargocd-cm: how often apps re-check Git
ARGOCD_CONTROLLER_REPLICAS=NMust equal the controller replica count when sharding
--status-processors / --operation-processorsController concurrency (defaults 20 and 10)
hydrator.enabled: "true"argocd-cmd-params-cm: turn on the source hydrator (beta)

Common pitfalls

  • Leaving everything in the default project, so any repo can deploy anything anywhere.
  • Fighting the HPA: Argo CD resets replicas on every sync unless you drop it from Git or add an ignoreDifferences rule.
  • Relying on three-minute polling instead of configuring Git webhooks, then wondering why deploys lag.
  • Deleting an ApplicationSet or an Application with the resources finalizer and taking production down with it.
  • Tracking the stable manifests in production instead of pinning a release.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →