GitOps: Principles, Argo CD, Flux, Drift, Image Automation
"Software agents continuously observe actual system state and attempt to apply the desired state." — OpenGitOps, GitOps Principles v1.0.0, principle 4 "Continuously Reconciled"
Summary: GitOps means the cluster pulls its desired state from a versioned store (usually a Git config repository) and an agent inside the cluster keeps live state equal to it: CI stops deploying and starts proposing commits, every change is a reviewed diff, drift is detected and reverted, and a rollback is a git revert. Argo CD and Flux are the two CNCF-graduated agents that do this for Kubernetes. Focus: The four OpenGitOps principles (declarative, versioned and immutable, pulled automatically, continuously reconciled), push vs pull deployment, the reconciliation loop and drift, repository layouts (config repository vs app repository, monorepo vs repo per environment, per-environment directories with Kustomize overlays or Helm values per env, and why branches per environment are an anti-pattern), Argo CD in depth (api-server, repo-server, application-controller, Redis; Application CRD and AppProject; sync policy with automated sync, prune and selfHeal; sync options; sync waves and sync hooks PreSync/PostSync; health status Healthy, Progressing, Degraded; OutOfSync and ignoreDifferences; ApplicationSet with the git, cluster, matrix and pull request generators; app of apps; Argo CD RBAC and SSO; Argo CD Notifications; Argo CD Image Updater), Flux in depth (source-controller, kustomize-controller, helm-controller, notification-controller, image-reflector-controller, image-automation-controller; GitRepository, OCIRepository, Kustomization with dependsOn and health checks, HelmRelease with drift detection, Receiver, Alert and Provider; ImageRepository, ImagePolicy and ImageUpdateAutomation that write back to Git; flux bootstrap; multi-tenancy), drift detection and self-heal, secrets in GitOps, environment promotion (image tag bump PR, Kargo), rollback by revert vs argocd app rollback, progressive delivery, OCI artifacts as sources, GitOps for infrastructure (Crossplane, Tofu Controller), sync metrics in Prometheus, and the anti-patterns. Learning goal: Lay out a config repository for a Go service and a Laravel app with one overlay per environment; deliver both with Argo CD (Applications, an AppProject, an ApplicationSet) or with Flux (Kustomizations, a HelmRelease, image automation of the Laravel tag); order migrations and smoke tests with hooks; promote from staging to prod by pull request; decide when self-heal must be on and when off; and debug a sync that is OutOfSync, Degraded or stuck.
This chapter is the delivery half of the Delivery & Infrastructure group. What it builds on: rendering manifests with Kustomize overlays and Helm charts is Packaging for Kubernetes (this page uses overlays, it does not re-teach them); the pipeline that builds, tests, scans and signs the image, and the OIDC trust between CI and the registry, is CI/CD Pipelines; canary, blue-green and rollback strategies at the traffic level are Deployment Strategies; Sealed Secrets, SOPS and the External Secrets Operator are owned by Kubernetes Config, Secrets & Storage; the RBAC that limits what an agent may touch is Kubernetes Security; Deployments, probes and rollouts are Kubernetes Workloads; the images themselves are Images & Dockerfiles; Terraform state and plan/apply are Infrastructure as Code; branching models and pull requests are Git & Version Control. The architectural view of why an organisation runs Kubernetes at all is Containers & Kubernetes; audit, change management and incident process are Secure SDLC & Incident Response.
Versions checked on 2026-11-29: Argo CD v3.6.3 (latest release, 24 Nov 2026), Flux v2.10.1 (20 Nov 2026), Argo CD Image Updater v1.x (CRD-based), OpenGitOps Principles v1.0.0. No cluster exists in this build environment: every argocd, flux and kubectl apply command on this page is expected, not run; the overlays were rendered and the Go tools were run for real on the host (see Lab).
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why pull beats push for deployments | Why it exists |
| Flux 2016, Argo 2017, OpenGitOps 1.0, CNCF graduation | Where it comes from |
| Declarative, versioned and immutable, pulled automatically, continuously reconciled | OpenGitOps principles |
| Push vs pull deployment | Push vs pull |
| Desired state, reconciliation loop, drift | Reconciliation loop |
| Config repository vs app repository, monorepo, per-environment directories, branches per environment anti-pattern, Kustomize overlays, Helm values per env | Repository layouts |
| api-server, repo-server, application-controller, Redis | Argo CD architecture |
| Application CRD, AppProject | Applications and projects |
| Sync policy, automated sync, prune, selfHeal, sync options | Sync policy |
| Sync waves, sync hooks, PreSync PostSync | Waves and hooks |
| Health status: Degraded Progressing Healthy; OutOfSync | Health and sync status |
| ignoreDifferences, diffing | Diffing |
| ApplicationSet: git generator, cluster generator, matrix generator, pull request generator; app of apps | ApplicationSet and app of apps |
| Argo CD RBAC, SSO, Argo CD Notifications | RBAC, SSO, notifications |
| Argo CD Image Updater | Image Updater |
| source-controller, kustomize-controller, helm-controller, notification-controller, image controllers | Flux controllers |
| GitRepository, OCIRepository, OCI artifacts | Flux sources |
| Kustomization, dependsOn, health checks | Flux Kustomization |
| HelmRelease | HelmRelease |
| Receiver, Alert Provider | Flux notifications |
| ImageRepository, ImagePolicy, ImageUpdateAutomation, write back to Git | Flux image automation |
| flux bootstrap, multi-tenancy | Bootstrap and multi-tenancy |
| Drift detection, self-heal, manual changes reverted | Drift and self-heal |
| Secrets in GitOps: SOPS link, Sealed Secrets link, ESO link | Secrets |
| Environment promotion, image tag bump PR, Kargo | Promotion |
Rollback by revert vs argocd app rollback | Rollback |
| Argo Rollouts link, Flagger link | Progressive delivery |
| Crossplane preview, tf-controller | GitOps for infrastructure |
| Sync metrics, Prometheus | Observability |
| kubectl apply from CI anti-pattern, cluster-admin CI, long-lived branches | Anti-patterns |
| One reconcile step by step, knobs, status reasons | Mechanics |
| Code | Go, Laravel |
| Classic problems and fixes | Solving the classic problems |
| Argo CD or Flux, which layout, which image automation | Choosing |
| From one cluster to a fleet | In architecture |
| Commands with real and expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The four OpenGitOps principles (v1.0.0, 8 Oct 2021).
| Principle | Exact wording | Plain words | What breaks it |
|---|---|---|---|
| Declarative | "A system managed by GitOps must have its desired state expressed declaratively." | Files describe the end state, not the steps | Deploy scripts, kubectl set image in a pipeline |
| Versioned and Immutable | "Desired state is stored in a way that enforces immutability, versioning and retains a complete version history." | Every change is a commit; history cannot be rewritten | Force-pushes to main, mutable latest tags, remote bases at HEAD |
| Pulled Automatically | "Software agents automatically pull the desired state declarations from the source." | The cluster fetches; nobody pushes into it | CI holding a kubeconfig and running kubectl apply |
| Continuously Reconciled | "Software agents continuously observe actual system state and attempt to apply the desired state." | Not once per pipeline run: forever, including after drift | Agents with self-heal off and nobody watching OutOfSync |
Argo CD and Flux in one table.
| Concern | Argo CD | Flux |
|---|---|---|
| Unit of delivery | Application (source + destination + sync policy) | Kustomization or HelmRelease pointing at a source object |
| Grouping and guard rails | AppProject (source repos, destinations, allowed kinds, roles) | Kubernetes namespaces + RBAC; serviceAccountName impersonation |
| Fan-out | ApplicationSet generators; app of apps | Kustomizations that create Kustomizations; one per cluster dir |
| Default poll | 120 s + up to 60 s jitter (timeout.reconciliation) | Per object .spec.interval (Kustomization "every five minutes by default" in the concepts page; you set it) |
| Drift correction | selfHeal: true (off by default) | Always on for Kustomizations at each interval; driftDetection.mode for HelmRelease |
| Ordering | Sync waves + hooks (PreSync, Sync, PostSync, SyncFail, PreDelete, PostDelete) | dependsOn between Kustomizations/HelmReleases; wait / healthChecks |
| Helm | Rendered with helm template; not in helm list | Real Helm release by helm-controller; in helm list |
| UI and users | Web UI, SSO (Dex or OIDC), Casbin RBAC | No built-in UI; Kubernetes RBAC; CLI flux |
| Image automation | Argo CD Image Updater (separate project, ImageUpdater CR) | image-reflector-controller + image-automation-controller (--components-extra) |
| Notifications | Argo CD Notifications (argocd-notifications-cm, triggers) | notification-controller: Alert, Provider, Receiver |
| Promotion | Not built in (Kargo, PR bots, Image Updater write-back) | Not built in (image automation to a PR branch, Kargo, CI) |
Statuses you will read every day.
| Status | Tool | Meaning | First thing to check |
|---|---|---|---|
| Synced | Argo CD | Live matches what Git renders | Nothing; check Health too |
| OutOfSync | Argo CD | At least one object differs or is missing | argocd app diff (expected, not run) |
| Healthy / Suspended / Progressing / Missing / Degraded / Unknown | Argo CD | Workload health, independent of sync status; the app takes the worst child (that order is most to least healthy) | Rollout, probes, events |
| Ready=True | Flux | Last reconcile applied and (with wait) health-checked | flux get kustomizations |
Ready=False, reason BuildFailed, HealthCheckFailed, DependencyNotReady | Flux | Build error, unhealthy workload, or a dependsOn not ready | flux events, flux tree |
| OutOfSync with a resource marked for pruning | Argo CD | Tracked as the app's, gone from Git, and prune is off ("The app will be out of sync if Argo CD expects a resource to be pruned") | Enable prune, or sync once with prune checked |
Why it exists
The usual first pipeline deploys by pushing: a CI job holds a kubeconfig, runs kubectl apply (or helm upgrade) and goes green. It works on day one. On day ninety nobody can say what runs in production without asking the cluster, because a hotfix was kubectl edited at 2 a.m.; the CI system holds credentials that can delete every namespace; the cluster API must be reachable from a CI provider's network; a deleted manifest leaves its Deployment running forever; and "roll back" means re-running an old pipeline and hoping it still builds.
GitOps turns the direction around. The only write path into the cluster is an agent that runs inside it and pulls; humans and CI change a repository; the agent makes the cluster match the repository and keeps it matched. The repository becomes the audit log, the review gate, the rollback mechanism and the disaster-recovery plan for the cluster's configuration at once.
| Simpler choice | Richer choice | What you buy | What you pay |
|---|---|---|---|
CI runs kubectl apply | Agent in the cluster pulls | No cluster credentials in CI, no inbound API access, drift visible | One more system to run and upgrade (Argo CD or Flux) |
| Apply once per pipeline run | Continuous reconciliation | Manual changes reverted, deleted objects pruned | Emergency kubectl edit is undone unless you suspend first |
| Manifests next to the code | Separate config repository | Clean audit log, separate access, no CI loops | A second repo and a promotion step |
| One branch per environment | One directory per environment on main | Diffs between envs are visible; no merge drift | Discipline in overlays |
| Mutable tags | Tags plus digests in Git | The commit names exact bytes; rollback is exact | Tooling to write digests |
| Manual tag bumps | Image automation or promotion bots | Fast staging; PR-gated prod | Bot credentials with write access to Git |
The analogy used through this page: a thermostat with a logbook. The logbook (the config repository) says "21 °C in every room"; only signed, dated entries are allowed and old entries are never erased. The thermostat (the agent) reads the logbook, measures each room (live state) and switches the heater until the reading matches. If someone opens a window (a kubectl edit), the thermostat notices the drift and corrects it; to change the temperature you write a new entry, not turn the radiator by hand. Rolling back is writing yesterday's entry again. The heating engineer (CI) never touches the radiators; they install better heaters (images) and propose logbook entries.
Three common misunderstandings, up front
- "GitOps means storing YAML in Git." Every team does that. The difference is principles 3 and 4: an agent pulls and keeps reconciling. A repository applied by a CI job is "Git-backed push", not GitOps. See Push vs pull.
- "Argo CD reverts manual changes by default." It does not: "By default, changes that are made to the live cluster will not trigger automated sync" until
selfHeal: true, and automated sync itself is opt-in. Flux's kustomize-controller, in contrast, re-applies at every interval. See Drift and self-heal. - "A rollback is clicking History → Rollback." In Argo CD, "Rollback cannot be performed against an application with automated sync enabled", and even when allowed it leaves Git and the cluster disagreeing. The GitOps rollback is
git revert. See Rollback.
Where it comes from
| When | What happened | Source |
|---|---|---|
| 2016 | Flux "was initially developed by Weaveworks and made open source in 2016" | Flux v1 README, History |
| 2017 | Argo "Created and open sourced in 2017 by Applatix, which was acquired by Intuit" | CNCF Argo graduation announcement |
| 2019 | "in 2019 Weaveworks decided to donate the project to CNCF" (Flux) | Flux v1 README |
| April 2020 | Argo "accepted into the CNCF Incubator in April 2020" | CNCF announcement |
| 8 Oct 2021 | OpenGitOps Documents v1.0.0: "the first full release of the Principles and Glossary by the GitOps Working Group" | open-gitops/documents releases |
| Argo CD v2.3 | "Starting with Argo CD v2.3, the ApplicationSet controller is bundled with Argo CD" | ApplicationSet docs |
| 30 Nov 2022 | Flux graduates; "It is the 18th CNCF project to graduate" | CNCF announcement |
| 6 Dec 2022 | Argo (Workflows, Events, Argo CD, Argo Rollouts) graduates | CNCF announcement |
| Flux v2 | Flux v1 "has reached end of life and has been replaced by fluxcd/flux2 and its controllers entirely" | Flux v1 README |
| Image Updater v1.0.0 | "a major transition from an annotation-based configuration to a CRD-based configuration" (ImageUpdater CR) | Argo CD Image Updater docs |
| Argo CD 3.x | Annotation tracking (argocd.argoproj.io/tracking-id) is the default tracking method | Resource tracking docs |
| Nov 2026 | Argo CD v3.6.3 (24 Nov), Flux v2.10.1 (20 Nov) | GitHub releases |
The word "GitOps" itself is usually credited to a 2017 Weaveworks blog post; that post's domain no longer serves it, so this page does not quote it and relies on OpenGitOps for the definitions. Two lineages explain the two tools' shapes. Flux grew out of a single operator that synced a repository and later split into the GitOps Toolkit: small controllers with one CRD family each, no UI, Kubernetes RBAC for everything. Argo CD was built as an application-delivery product with a UI, its own users and RBAC, and one central controller that can manage many clusters. Both now speak OCI artifacts as sources as well as Git.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.
OpenGitOps principles: declarative, versioned and immutable, pulled automatically, continuously reconciled Must-know
In plain words: Write down what you want, keep every version of it, let a program in the target system fetch it, and let that program keep fixing the system until it matches.
Common misunderstanding: "Git is mandatory." The glossary defines a state store as "A system for storing immutable versions of desired state declarations" and adds: "Git, from which GitOps derives its name, is the canonical example used as this state store but any other system that meets these criteria may be used." An OCI registry holding signed, immutable config artifacts qualifies; Flux calls that "Gitless GitOps".
Definition: The OpenGitOps principles say the desired state of a GitOps-managed system must be declarative, versioned and immutable, pulled automatically and continuously reconciled. The glossary defines desired state as "The aggregate of all configuration data that is sufficient to recreate the system so that instances of the system are behaviourally indistinguishable", explicitly not including "persistent application data, eg. database contents". Continuous "is intended to match the industry standard term: reconciliation continues to happen, not that it must be instantaneous."
Day in the life of one change under the four principles
1 developer opens a PR: apps/orders-api/overlays/prod newTag 1.4.2 -> 1.5.0 (declarative)
2 review + merge: commit c4f1e9a on main, signed, never rewritten (versioned and immutable)
3 agent in the prod cluster fetches main at its next poll or on a webhook (pulled automatically)
4 agent diffs, applies, then keeps comparing every few minutes (continuously reconciled)
5 someone runs kubectl scale --replicas=0 at 02:00 -> next comparison reverts it (drift corrected)Real scenarios:
- An auditor asks who changed the payment service's resource limits in March:
git log -p apps/payments/answers with names, reviewers and timestamps. - A cluster is lost: a new cluster bootstrapped against the same repository converges to the same desired state (persistent data comes from backups, not from Git).
- A team "does GitOps" by running
kubectl apply -kfrom GitHub Actions: principles 3 and 4 fail; drift is invisible. - A config repo whose base uses a remote Kustomize base at
HEADviolates "immutable": the same commit renders differently next week.
| Product | How it meets the four principles |
|---|---|
| Argo CD | Declarative Application CRs; Git/Helm/OCI sources at a revision; application-controller pulls and compares; self-heal optional |
| Flux | Source objects pull Git/OCI/Helm/Bucket; Kustomization/HelmRelease reconcile on .spec.interval; drift corrected by default for Kustomizations |
| Kargo | Builds on an agent (Argo CD); adds promotion of desired state between stages, not reconciliation |
Plain CI + kubectl apply | Declarative and versioned, but pushed and applied once: not GitOps |
Fix / how to use it: treat the four principles as a checklist for every path into the cluster. If any path writes to the cluster without going through the state store (a CI job, a person with cluster-admin, an operator UI), either remove it or make it visible as drift.
Push vs pull deployment Must-know
In plain words: Push: the pipeline reaches into the cluster. Pull: the cluster reaches out to the repository.
Common misunderstanding: "Pull is just a security detail." It changes who can see drift. A push pipeline only acts when it runs; the glossary's definition of pull says agents "must be able to access the desired state from the state store at any time, not only when there is an intentional change in the state store triggering a push event", which "is a prerequisite for reconciliation to happen continuously".
Definition: In push deployment an external system (CI, a deploy tool) holds cluster credentials and applies changes when a pipeline runs. In pull deployment an agent inside the target pulls desired state and applies it itself; external systems only write to the state store. Argo CD's auto-sync page states the consequence: "CI/CD pipelines no longer need direct access to the Argo CD API server to perform the deployment. Instead, the pipeline makes a commit and push to the Git repository".
push pull
1 CI: build + push image 1 CI: build + push image
2 CI: kubectl apply (cluster-admin token) 2 CI (or bot): commit new tag to config repo
3 done; nothing watches the cluster 3 agent: poll/webhook -> fetch -> diff -> apply
4 agent: repeat forever; report Synced/HealthyReal scenarios:
- A private EKS/GKE cluster with no public API endpoint: push CI needs a VPN or a self-hosted runner inside the VPC; a pull agent needs only egress to Git and the registry.
- A leaked CI secret in a push setup is a cluster takeover; in pull, the worst case is a malicious commit, which still needs review and leaves a trace.
- A fleet of 40 edge clusters behind NAT: only pull scales; each cluster fetches the same repository.
| Aspect | Push (CI deploys) | Pull (agent reconciles) |
|---|---|---|
| Credentials | Cluster credentials in CI | Git/registry read credentials in the cluster |
| Network | CI must reach the API server | Cluster must reach Git/registry (egress only) |
| Drift | Invisible until the next run | Detected on every reconcile |
| Prune | Only if the script deletes | prune: true deletes what left Git |
| Audit | CI logs | Git history + agent events |
| Speed of a change | Immediate when the job runs | Poll interval or webhook (seconds) |
Fix: move the kubectl apply out of CI (see the Before workflow in Go); give CI write access to the config repository (or let it open PRs) and give the cluster an agent.
Desired state, the reconciliation loop and drift Must-know
In plain words: The agent repeats three steps forever: read what should be, look at what is, change what is to match.
Common misunderstanding: "Reconciliation happens when I push." A push (or a webhook) only makes the next loop happen sooner. OpenGitOps: "in GitOps, reconciliation is triggered whenever there is a divergence", and divergence "could be due to the actual state unintentionally drifting from the desired state declarations – not only due to a new desired state declaration version having been changed intentionally."
Definition: Reconciliation is "The process of ensuring the actual state of a system matches its desired state." Drift is "When a system's actual state has moved or is in the process of moving away from the desired state". The loop is a control loop with feedback: OpenGitOps "follows control-theory and operates in a closed-loop".
reconcile(app), every interval or on an event
1 fetch source at revision R (Git commit / OCI digest) -> artifact
2 render: kustomize build | helm template | plain YAML -> desired objects D
3 read live objects L that the app owns (tracking label/annotation)
4 diff(D, L) ignoring server-set fields and ignore rules
5 if diff and policy allows: apply (create/patch), prune objects in L but not in D
6 wait for health (rollout complete, Jobs succeeded) -> report status, emit events
7 requeue after interval; a new revision or a webhook requeues immediatelyReal scenarios:
- An HPA scales a Deployment to 7 replicas; the Deployment manifest in Git says 2: without an ignore rule (or omitting
replicas), every loop fights the HPA. - A mutating webhook (a service-mesh sidecar injector) adds containers: the diff must ignore what other controllers own.
- An operator rotates a certificate Secret it manages: that Secret must not be in Git at all.
| Product | Loop trigger | Interval knob |
|---|---|---|
| Argo CD | Poll, Git webhook to /api/webhook, manual refresh | timeout.reconciliation (120 s default) + timeout.reconciliation.jitter (60 s) in argocd-cm |
| Flux Kustomization | .spec.interval, new source revision, Receiver webhook, flux reconcile | .spec.interval (required; "minimum value should be 60 seconds"), .spec.retryInterval |
| Flux sources | .spec.interval per GitRepository/OCIRepository | Same |
Fix: keep fields that other controllers own out of Git (replicas under an HPA), or tell the agent to ignore them; configure webhooks so the poll interval is a safety net, not the delivery path. The Go section has a small drift model you can run.
Repository layouts: config repository vs app repository, monorepo, per-environment directories Must-know
In plain words: Keep the deployment configuration in its own repository, with one directory per environment on a single branch, and let overlays express the differences.
Common misunderstanding: "One branch per environment (dev, staging, prod) is the natural Git way." It is the branches per environment anti-pattern: the differences between environments hide in merge history, cherry-picks drift, a merge from staging to prod drags unrelated changes along, and nobody can diff "what is different in prod" with one command. Flux's monorepo guide stores "The various environments specific configs are all stored in the same branch (e.g. main)" and keeps other branches short-lived: "once a pull request is merged, the branch gets deleted."
Definition: An app repository holds source code (and maybe a base manifest or a chart); a config repository holds the deployable desired state for one or more apps and clusters. Argo CD's best practices "highly recommended" a separate config repository for: a clean separation of code and config, "Cleaner audit log", apps built from several repositories, "Separation of access", and avoiding "an infinite loop of build jobs and Git commit triggers". Flux's repository guide names four shapes: monorepo, repo per environment, repo per team, repo per app. Per-environment directories use Kustomize overlays (a base plus overlays/staging, overlays/prod) or Helm values per env (values-staging.yaml, values-prod.yaml); both are taught in Packaging for Kubernetes.
shop-config/ (this chapter's snippet tree, docs/snippets/platform/gitops-argocd-flux/config-repo)
apps/orders-api/base/ Go service: Deployment, Service, image name
apps/orders-api/overlays/staging namespace, 1 replica, tag 1.5.0 (Image Updater writes here)
apps/orders-api/overlays/prod namespace, tag 1.4.2 + digest (promotion PRs write here)
apps/orders-api/overlays/preview no namespace: each PR Application sets orders-api-pr-<n>
apps/shop-laravel/base/ web (php-fpm + Nginx) and worker Deployments, Service
apps/shop-laravel/release-jobs/ migrate Job (PreSync), smoke Job (PostSync)
apps/shop-laravel/overlays/* tags with Flux $imagepolicy markers
infrastructure/namespaces/ cluster-scoped objects, reconciled first
argocd/ AppProjects, Applications, ApplicationSets, cluster Secret, Image Updater, config maps
clusters/staging, clusters/prod Flux objects per cluster (bootstrap path)
tenants/ Flux multi-tenancy onboardingReal scenarios:
- Bumping replicas in prod should not trigger a 20-minute application build: a separate config repo keeps the two pipelines apart.
- Contractors may push to the app repo but not change production: separate repositories give separate access, which branch protections alone do not (Flux: "Git is not designed to restrict access to certain files in a repository").
- A team with strict prod change control chooses repo per environment (a dedicated production repository that "limits the scope of changes").
- A platform team owns
infrastructure/andclusters/; app teams ownapps/<name>/via CODEOWNERS (the repo per team variant moves that split into separate repositories).
| Layout | Fits | Watch out |
|---|---|---|
| Monorepo, directories per env, one branch | Most teams; one place to see everything | CODEOWNERS for prod paths; big PRs hide prod changes |
| Repo per environment | Strict prod access, regulated environments | Promotion is a cross-repo PR; infra changes are slower |
| Repo per team | Platform team + autonomous app teams | Platform must onboard each repo (Flux GitRepository, Argo CD source repo in the AppProject) |
| Repo per app (manifests in the app repo) | Tiny setups, libraries of manifests used as bases | CI commit loops, noisy audit log; config repo should reference it, not copy it |
| Branch per environment | Nothing recommended | Merge drift, hidden differences, long-lived branches |
The tree holds both an Argo CD side (argocd/) and a Flux side (clusters/, tenants/) so the chapter can show each tool against the same overlays. They are alternatives: a real cluster runs one agent per namespace, and two agents reconciling shop-staging would fight over every object.
Fix: start with the monorepo layout above: main only, one overlay per environment, CODEOWNERS on overlays/prod and argocd/, and a CI job that renders every overlay on every PR (Go has the policy tests).
Argo CD architecture: api-server, repo-server, application-controller, Redis Must-know
In plain words: Three main processes: one answers people and tools, one renders manifests from Git, one compares and syncs. Redis caches.
Common misunderstanding: "Argo CD applies through its API server, so the UI must be up for deployments." The application-controller reconciles on its own; the api-server is for users, the CLI, CI and webhooks.
Definition (Argo CD architecture page): the api-server "is a gRPC/REST server which exposes the API consumed by the Web UI, CLI, and CI/CD systems", responsible for application management, "invoking of application operations (e.g. sync, rollback, user-defined actions)", credential management "stored as K8s secrets", authentication and auth delegation, "RBAC enforcement" and the "listener/forwarder for Git webhook events". The repo-server "maintains a local cache of the Git repository holding the application manifests" and generates manifests from repository URL, revision, application path and "template specific settings: parameters, helm values.yaml". The application-controller "continuously monitors running applications and compares the current, live state against the desired target state ... It detects OutOfSync application state and optionally takes corrective action" and invokes hooks "(PreSync, Sync, PostSync)". Redis: "Redis is only used as a disposable cache and can be safely rebuilt without service disruption" (HA docs). Alongside run argocd-dex-server (SSO), the ApplicationSet controller and the notifications controller.
Webhook-triggered sync of orders-api-staging
1 GitHub -> POST https://argocd.acme.internal/api/webhook (argocd-server)
2 argocd-server: refresh apps whose source repo matches
3 application-controller: ask repo-server for manifests of path overlays/staging at main@c4f1e9a
4 repo-server: git fetch (cached), kustomize build -> manifests (cached by revision)
5 controller: diff vs live objects (watched through its cluster cache) -> OutOfSync
6 automated sync: waves/hooks, kubectl-equivalent apply -> Synced, health Progressing -> Healthy
7 notifications-controller: trigger conditions evaluated -> Slack message if a trigger firesReal scenarios:
- repo-server CPU spikes when a monorepo with hundreds of Helm apps changes: scale repo-server replicas; caches are keyed by revision.
- One Argo CD instance manages 30 clusters: application-controller memory grows with watched resources; the HA docs describe sharding controllers by cluster.
- Redis is lost: no data loss, only cache rebuild.
| Component | Workload | Scales by |
|---|---|---|
argocd-server | Deployment | Replicas (stateless) |
argocd-repo-server | Deployment | Replicas; rendering is CPU-bound |
argocd-application-controller | StatefulSet | Shards (clusters split across replicas) |
argocd-redis | Deployment (HA manifests: Redis HA) | Disposable cache |
argocd-dex-server | Deployment | Only if Dex is used |
| ApplicationSet and notifications controllers | Deployments | Usually one each |
Fix: install the HA manifests for production, put argocd-server behind your Ingress with SSO, configure the Git webhook, and keep Argo CD's own configuration (projects, RBAC, notification ConfigMaps) in Git too.
The Application CRD and the AppProject Must-know
In plain words: An Application says "render this path of this repo and keep it in that namespace of that cluster". An AppProject says which repos, clusters, namespaces and kinds Applications in it may use.
Common misunderstanding: "The default project is fine." It "permits deployments from any source repo, to any cluster, and all resource Kinds"; the docs recommend "to create dedicated projects with explicit source, destination, and resource permissions." And: "Projects which can deploy to the Argo CD namespace grant admin access".
Definition: The Application CRD ("A group of Kubernetes resources as defined by a manifest. This is a Custom Resource Definition (CRD).") has spec.source (repoURL, targetRevision, path, plus kustomize/helm/directory options), spec.destination (server or name, namespace), spec.project, spec.syncPolicy and spec.ignoreDifferences. The AppProject "is the Kubernetes resource object representing a logical grouping of applications", defined by sourceRepos, destinations and roles, plus cluster/namespace resource allow and deny lists and syncWindows.
Who may deploy what (shop project)
1 Application orders-api-prod: project shop, source shop-config.git, destination shop-prod
2 application-controller checks project shop: source repo allowed? yes
3 destination allowed? yes (shop-prod)
4 every kind allowed? Deployment yes, ClusterRole no
5 a PR adding a ClusterRoleBinding to the overlay -> sync refused for that resourceReal scenarios:
- A team's Application accidentally points at
kube-system: the project'sdestinationsrefuse it. - A chart quietly adds a
ClusterRole:clusterResourceWhitelist: []blocks it and the PR author learns it belongs to the platform layer. - CI needs to trigger a sync of staging only: a project role with
applications, sync, shop/*-stagingand a JWT token, nothing else.
| Field | Shop project value | Why |
|---|---|---|
sourceRepos | only shop-config.git | No app pulls YAML from a random repo |
destinations | shop-staging, shop-prod | Never argocd (admin-level) |
clusterResourceWhitelist | [] | Namespaces and CRDs come from the platform layer |
namespaceResourceWhitelist | Deployment, ReplicaSet, Pod, Service, ConfigMap, Job, HPA, PDB | Also controls what the UI tree shows |
roles | ci-sync-staging | Scoped token for CI |
syncWindows | allow prod 06:00-18:00 weekdays, manualSync: true | Change windows enforced by the agent |
Fix: one project per team or domain; the platform project is the only one allowed into argocd:
# AppProject: the guard rails for every shop Application. Never deploy apps through
# the "default" project, which allows any repo, any cluster and every kind.
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
name: shop
namespace: argocd
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
description: Shop services (orders-api, shop-laravel)
# only the config repository may be a source
sourceRepos:
- https://github.com/acme/shop-config.git
# only the shop namespaces; never the argocd namespace (that would be admin access)
destinations:
- namespace: shop-staging
server: https://kubernetes.default.svc
- namespace: shop-prod
server: https://prod-api.k8s.acme.internal
# no cluster-scoped kinds at all: namespaces come from the platform layer
clusterResourceWhitelist: []
namespaceResourceWhitelist:
- group: apps
kind: Deployment
- group: apps
kind: ReplicaSet
- group: ''
kind: Pod
- group: ''
kind: Service
- group: ''
kind: ConfigMap
- group: batch
kind: Job
- group: autoscaling
kind: HorizontalPodAutoscaler
- group: policy
kind: PodDisruptionBudget
roles:
# CI may sync staging apps (for an explicit "deploy now"), nothing else
- name: ci-sync-staging
description: Sync privileges for staging Applications only
policies:
- p, proj:shop:ci-sync-staging, applications, sync, shop/*-staging, allow
# prod changes only between 06:00 and 18:00 UTC on weekdays; manual syncs stay possible
syncWindows:
- kind: allow
schedule: "0 6 * * 1-5"
duration: 12h
applications:
- "*-prod"
manualSync: true# Two more projects. "platform" may manage Argo CD's own namespace, which makes it
# admin-level: only platform admins push to argocd/ and sync this project.
# "shop-previews" may deploy only into orders-api-pr-* namespaces.
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
name: platform
namespace: argocd
spec:
description: Argo CD's own objects (projects, ApplicationSets, Applications)
sourceRepos:
- https://github.com/acme/shop-config.git
destinations:
- namespace: argocd
server: https://kubernetes.default.svc
clusterResourceWhitelist: []
namespaceResourceWhitelist:
# cluster registration Secrets (argocd.argoproj.io/secret-type: cluster)
- group: ''
kind: Secret
- group: argoproj.io
kind: AppProject
- group: argoproj.io
kind: Application
- group: argoproj.io
kind: ApplicationSet
- group: argocd-image-updater.argoproj.io
kind: ImageUpdater
---
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
name: shop-previews
namespace: argocd
spec:
description: Short-lived pull-request environments for orders-api
sourceRepos:
- https://github.com/acme/shop-config.git
destinations:
- namespace: 'orders-api-pr-*'
server: https://kubernetes.default.svc
# CreateNamespace=true needs Namespace in the cluster-scoped allow list
clusterResourceWhitelist:
- group: ''
kind: Namespace
namespaceResourceWhitelist:
- group: apps
kind: Deployment
- group: apps
kind: ReplicaSet
- group: ''
kind: Pod
- group: ''
kind: ServiceSync policy: automated sync, prune, selfHeal and sync options Must-know
In plain words: Automated sync applies new commits by itself; prune also deletes what you removed from Git; selfHeal also undoes changes made in the cluster.
Common misunderstanding: "automated: {} gives me full GitOps." Three safety defaults remain: no pruning ("By default (and as a safety mechanism), automated sync will not delete resources when Argo CD detects the resource is no longer defined in Git"), no self-heal, and no empty apps ("automated sync with prune have a protection from any automation/human errors when there are no target resources", unless allowEmpty: true).
Definition: spec.syncPolicy.automated turns on automated sync (enabled: false keeps the fields but skips it). prune: true deletes extraneous resources; selfHeal: true syncs "when the live cluster's state deviates from the state defined in Git", retried "after self-heal timeout (5 seconds by default)" (--self-heal-timeout-seconds). retry sets the backoff (limit, backoff.duration, factor, maxDuration); without it, the Application spec reference says "automated sync by default retries failed attempts 5 times with following delays between attempts ( 5s, 10s, 20s, 40s, 80s )". Semantics from the docs: automated sync runs "only if the application is OutOfSync"; it "will only attempt one synchronization per unique combination of commit SHA1 and application parameters", unless self-heal is on; once those retries are used up, "Automatic sync will not reattempt a sync if the previous sync attempt against the same commit-SHA and parameters had failed" (a new commit or a manual sync is needed). Sync options (in syncOptions or per resource via argocd.argoproj.io/sync-options): Prune=false, Prune=confirm, Delete=false, Validate=false, SkipDryRunOnMissingResource=true, ApplyOutOfSyncOnly=true, PrunePropagationPolicy=foreground|background|orphan, PruneLast=true, Replace=true (potentially destructive), Force=true (with Replace), ServerSideApply=true (uses kubectl apply --server-side --force-conflicts), FailOnSharedResource=true, RespectIgnoreDifferences=true, CreateNamespace=true.
Same commit, three policies; someone ran kubectl scale deploy/orders-api --replicas=0
automated:{} +prune +selfHeal
1 new commit arrives synced synced synced
2 manifest deleted resource stays (OOS) resource deleted resource deleted
3 kubectl scale 0 OutOfSync, no action OutOfSync, no act. re-synced after ~5 sReal scenarios:
- A PersistentVolumeClaim must survive app deletion:
Delete=falseon that resource. - A Namespace must never be pruned by accident:
Prune=confirmon it. - A huge CRD exceeds the 262144-byte
last-applied-configurationannotation limit:ServerSideApply=true. - Two Applications render the same ConfigMap:
FailOnSharedResource=trueturns a silent tug-of-war into a failed sync.
| Policy field / option | Default | Use when |
|---|---|---|
automated | Off | Every environment that should follow Git without a click |
automated.prune | false | Always in GitOps; protect individual objects with Prune=false/confirm |
automated.selfHeal | false | Production with no manual changes allowed; see when to turn it off |
automated.allowEmpty | false | Rarely; keeps a bad commit from deleting everything |
retry.limit | automated sync: 5 retries at 5/10/20/40/80 s | Set explicitly (e.g. limit: 5, maxDuration: 3m) so the behaviour is visible in Git; -1 = unlimited |
ServerSideApply=true | client-side apply | Large objects, shared field ownership |
ApplyOutOfSyncOnly=true | apply every object | Apps with thousands of objects |
CreateNamespace=true | fail if namespace missing | Ad-hoc envs (previews); not when the platform owns namespaces |
Fix: the Go service's prod Application, written out in full (the brief's "Go service Application"). The shop ApplicationSet below generates the same object, so the root app excludes this file; a real repository keeps one or the other:
# The Go service in prod as one Argo CD Application, written out by hand to show every
# field. In this repository the shop ApplicationSet generates the same Application, so
# the root app excludes this file; use one or the other, never both.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: orders-api-prod
namespace: argocd
finalizers:
# deleting the Application deletes its resources (cascading delete)
- resources-finalizer.argocd.argoproj.io
annotations:
notifications.argoproj.io/subscribe.on-sync-failed.slack: shop-deploys
notifications.argoproj.io/subscribe.on-health-degraded.slack: shop-deploys
spec:
project: shop
source:
repoURL: https://github.com/acme/shop-config.git
targetRevision: main
path: apps/orders-api/overlays/prod
destination:
server: https://prod-api.k8s.acme.internal
namespace: shop-prod
syncPolicy:
automated:
# delete objects that were removed from Git
prune: true
# revert manual changes in the cluster (drift) without waiting for a new commit
selfHeal: true
syncOptions:
- ServerSideApply=true
- PruneLast=true
# the namespace comes from the platform layer, not from this app
- CreateNamespace=false
retry:
limit: 5
backoff:
duration: 5s
factor: 2
maxDuration: 3m
# an HPA owns spec.replicas in prod; do not report it as drift
ignoreDifferences:
- group: apps
kind: Deployment
jsonPointers:
- /spec/replicas
revisionHistoryLimit: 10Sync waves and sync hooks: PreSync PostSync, SyncFail, PreDelete, PostDelete Must-know
In plain words: Hooks run Jobs before, after or instead of a sync step (migrations before, smoke tests after). Waves order normal resources by a number.
Common misunderstanding: "Helm hooks run as Helm hooks under Argo CD." Argo CD renders with helm template and maps Helm hook annotations onto its own phases; "delete-policy evaluation still follows Argo CD sync phases and sync result semantics rather than Helm's per-hook-event lifecycle."
Definition: argocd.argoproj.io/hook assigns a resource to a phase: PreSync "Executes prior to the application of the manifests"; Sync runs "at the same time as the application of the manifests"; Skip; PostSync "Executes after all Sync hooks completed and were successful, a successful application, and all resources in a Healthy state"; SyncFail "Executes when the sync operation fails"; PreDelete / PostDelete run only on Application deletion (PostDelete "Available starting in v2.10"). argocd.argoproj.io/hook-delete-policy: HookSucceeded, HookFailed, BeforeHookCreation (default if none is given). Sync waves (argocd.argoproj.io/sync-wave, an integer, default 0, may be negative): Argo CD applies the lowest wave first, waits for it to be healthy, then the next; "The current delay between each sync wave is 2 seconds" (ARGOCD_SYNC_WAVE_DELAY). Pruning runs waves in reverse. Hooks "do not run during a selective sync operation".
Sync of shop-laravel-staging at commit 9a1b (tag 2.8.1 -> 2.9.0)
1 PreSync Job shop-migrate: php artisan migrate --force --isolated -> Succeeded
2 Sync wave 0: Service, Deployments shop-web + shop-worker (new image) applied
3 wait: Deployments Progressing -> Healthy (readiness /up green)
4 PostSync Job shop-smoke: php artisan app:smoke-test -> Succeeded
5 sync result Succeeded; hooks with HookSucceeded deleted
if step 1 fails: whole sync stops, nothing new is applied, SyncFail hooks runReal scenarios:
- Database migrations before new pods start (PreSync Job), with migrations written backwards-compatible because old pods keep serving during the rollout.
- Smoke tests after rollout (PostSync) that fail the sync and page someone through the
on-sync-failedtrigger. - CRDs in wave -1, the operator in wave 0, its custom resources in wave 1.
- Removing a DNS record from an external system on app deletion (PostDelete).
| Concern | Argo CD | Flux |
|---|---|---|
| Before/after steps | PreSync / PostSync / SyncFail hooks | No phases; separate Kustomizations ordered with dependsOn, or Helm hooks inside a HelmRelease (real Helm) |
| Ordering of normal resources | Sync waves | dependsOn between Kustomizations (the docs' example: cert-manager CRDs and controller before the certs Kustomization) |
| Job re-runs | Hook recreated each sync (BeforeHookCreation) | Job template immutable: kustomize.toolkit.fluxcd.io/force: enabled recreates it |
| Wait for completion | Hooks must reach Healthy | wait: true or healthChecks include Jobs |
Fix: the Laravel release Jobs, readable by both agents:
apiVersion: batch/v1
kind: Job
metadata:
name: shop-migrate
annotations:
# Argo CD: run before any manifest of the sync is applied; a failure stops the sync
argocd.argoproj.io/hook: PreSync
# delete the previous run just before creating the new one (also Argo CD's default)
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
# Flux: Job templates are immutable; recreate the Job when the image tag changes
kustomize.toolkit.fluxcd.io/force: enabled
spec:
backoffLimit: 1
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: ghcr.io/acme/shop-app
# --force: no confirmation prompt in production; --isolated: a cache lock so two
# concurrent runs (two clusters, a retried sync) never migrate at the same time
command: ["php", "artisan", "migrate", "--force", "--isolated"]
envFrom:
- secretRef:
name: shop-laravel-envapiVersion: batch/v1
kind: Job
metadata:
name: shop-smoke
annotations:
# Argo CD: run after every resource is applied and Healthy; failure marks the sync failed,
# which fires the on-sync-failed notification trigger
argocd.argoproj.io/hook: PostSync
argocd.argoproj.io/hook-delete-policy: HookSucceeded
kustomize.toolkit.fluxcd.io/force: enabled
spec:
# Ordering does not come from retries: the command itself first polls the web Service's
# /version until it reports this image's version (needed under Flux, which has no hook
# phases), then checks DB, schema and cache. One retry covers a pod eviction.
backoffLimit: 1
template:
spec:
restartPolicy: Never
containers:
- name: smoke
image: ghcr.io/acme/shop-app
command: ["php", "artisan", "app:smoke-test", "--url=http://shop-web"]
envFrom:
- secretRef:
name: shop-laravel-envHealth status: Healthy, Progressing, Degraded (and OutOfSync is something else) Must-know
In plain words: Sync status answers "does the cluster match Git?"; health answers "does it work?". An app can be Synced and Degraded, or OutOfSync and Healthy.
Common misunderstanding: "Synced means deployed successfully." Synced only means the objects match; the new pods may be in CrashLoopBackOff. Watch health, and for Flux, Ready with wait: true.
Definition: Argo CD's core concepts: Sync status "Whether or not the live state matches the target state"; Health "is it running correctly? Can it serve requests?". Built-in checks: Deployments, ReplicaSets, StatefulSets and DaemonSets need observed generation equal to desired and updated replicas equal to desired; a Pod with restartPolicy: Always is "Degraded" if a container is in an error state "(e.g. CrashLoopBackOff, ImagePullBackOff)"; a Job-like Pod "is considered 'Progressing' while it is running". Statuses: Healthy, Progressing ("not healthy yet but still making progress"), Degraded, Suspended, plus Missing and Unknown; "The App health will be the worst health of its immediate child resources". Custom resources need Lua health checks in resource.customizations.health.<group>_<kind>. Flux health checks accept built-in kinds, Flux kinds and "Custom resources that are compatible with kstatus".
Rollout of orders-api 1.5.0 with a bad config value
t0 sync applies Deployment (generation 9 -> 10) sync: Synced health: Progressing
t+40 new pods CrashLoopBackOff, old ReplicaSet still up sync: Synced health: Degraded
t+41 on-health-degraded trigger -> Slack (Flux: Kustomization Ready=False, HealthCheckFailed)
t+60 fix = revert commit -> new sync sync: Synced health: HealthyReal scenarios:
- A Deployment whose probes always fail stays Progressing until
progressDeadlineSeconds, then Degraded. - An app-of-apps parent shows Healthy while a child is Degraded, because Application health assessment was removed in 1.8; the docs give a Lua customization to restore it.
- A Flux Kustomization without
waitorhealthChecksreports Ready right after apply, before any pod starts.
| Status | Argo CD wording | Flux equivalent |
|---|---|---|
| Healthy | "the resource is healthy" | Ready=True after health checks |
| Progressing | "not healthy yet but still making progress" | Ready=Unknown, reason Progressing |
| Degraded | "the resource is degraded" | Ready=False, reason HealthCheckFailed |
| Suspended | "waiting for some external event to resume" | .spec.suspend: true (reconciliation paused) |
| OutOfSync | live differs from target | drift corrected at the next interval (no separate status) |
Fix: give every workload real readiness probes (/readyz for the Go service, /up for Laravel), set wait: true or healthChecks in Flux, and subscribe to on-health-degraded.
Diffing and ignoreDifferences Important
In plain words: Some fields are legitimately changed by someone else; tell the agent not to count them as drift.
Common misunderstanding: "OutOfSync right after a successful sync means Argo CD is broken." The docs list the usual causes: extra unknown fields in the manifest that the API server drops, pruning disabled, "A controller or mutating webhook is altering the object", a Helm chart using randAlphaNum, and the HPA reordering spec.metrics.
Definition: spec.ignoreDifferences takes group, kind, optional name/namespace, and jsonPointers (RFC 6902; / in a key is written ~1), jqPathExpressions, or managedFieldsManagers (ignore fields owned by e.g. kube-controller-manager). System-wide: resource.customizations.ignoreDifferences.<group>_<kind> or .all in argocd-cm; resource.compareoptions with ignoreResourceStatusField (crd, all default, none). By default ignore rules affect only the comparison: "during the sync stage, the desired state is applied as-is" unless RespectIgnoreDifferences=true. Flux HelmRelease has driftDetection.ignore with JSON pointers; for Kustomizations, leave owned-elsewhere fields out of Git.
HPA vs Git, Application with and without ignoreDifferences on /spec/replicas
1 Git: replicas: 2 HPA scales to 7
2 no rule: OutOfSync; with selfHeal the agent sets 2, the HPA sets 7 again ... (flapping)
3 rule: Synced; HPA owns the field
4 better: omit replicas from Git entirely (Argo CD best practice: "do not include replicas")Real scenarios:
- Istio or Linkerd inject sidecars:
jqPathExpressionsselecting the injected container, ormanagedFieldsManagers. - A
MutatingWebhookConfigurationwhosecaBundlecert-manager rotates: the system-level example in the docs. - An operator writes
statusinto a CR committed to Git:ignoreResourceStatusField: crd.
| Need | Argo CD | Flux |
|---|---|---|
| Ignore one field | ignoreDifferences.jsonPointers | HelmRelease driftDetection.ignore.paths |
| Ignore another controller's fields | managedFieldsManagers | Server-side apply field ownership; don't set those fields |
| Keep a field untouched on sync too | RespectIgnoreDifferences=true | kustomize.toolkit.fluxcd.io/ssa: IfNotPresent (create-only) |
| Leave one object's fields alone during sync | ignoreDifferences on those fields + RespectIgnoreDifferences=true (Prune=false only stops deletion; sync still applies the desired state), or remove the object from the app's source | kustomize.toolkit.fluxcd.io/reconcile: disabled (no apply, no prune) |
Fix: see ignoreDifferences in the prod Application above; prefer removing the field from Git.
ApplicationSet: git generator, cluster generator, matrix generator, pull request generator; app of apps Must-know
In plain words: Instead of writing one Application per app per environment per cluster, write one template and let generators produce the parameters. App of apps is the older trick: one Application whose manifests are other Applications.
Common misunderstanding: "ApplicationSets are safe to hand to every team." The docs: "only admins may be given permission ... to create, update, or delete ApplicationSets", because they "can create Applications under arbitrary Projects" and the git generator "can read Secrets in the Argo CD namespace and send them to arbitrary URLs". The same holds for app of apps: "App of Apps is an admin-only tool".
Definition: The ApplicationSet controller (bundled since v2.3) renders spec.template once per parameter set from spec.generators. The generators page lists List, Cluster ("based on the list of clusters defined within (and managed by) Argo CD"), Git ("based on files within a Git repository, or based on the directory structure"), Matrix ("combine the generated parameters of two separate generators"), Merge, SCM Provider, Pull Request ("automatically discover open pull requests within an repository"), Cluster Decision Resource, Plugin and OCI. The git directory generator yields path.path, path.basename, path.basenameNormalized and path.segments; the cluster generator yields name, nameNormalized, server and metadata.labels.<key>; the PR generator yields number, branch, branch_slug, target_branch, head_sha, head_short_sha and labels, polling by default "every 30 minutes" (requeueAfterSeconds). The matrix "currently only supports combining the outputs of only two child generators", and a child can consume the parameters of the child before it. With goTemplate: true and missingkey=error, a typo fails the render instead of producing an Application named -staging. App of apps: "Declaratively specify one Argo CD app that consists only of other apps"; Argo CD's cluster-bootstrapping guide recommends ApplicationSets with the cluster generator and calls app of apps the alternative.
appset-shop: matrix(git directories apps/*/overlays/*, clusters with label env=<dir name>)
git child -> {path: apps/orders-api/overlays/staging, basename: staging, segments: [apps,orders-api,overlays,staging]}
{path: apps/orders-api/overlays/prod, ...} {path: apps/shop-laravel/overlays/staging, ...} {..prod..}
cluster child (per git item, selector env=<basename>) -> staging item: {name: in-cluster, server: https://kubernetes.default.svc}
matrix -> orders-api-staging, orders-api-prod, shop-laravel-staging, shop-laravel-prod
new overlay apps/payments/overlays/staging pushed -> payments-staging appears at the next generator run
cluster Secret relabelled -> its Applications move or disappear (and are deleted with their resources)Real scenarios:
- 12 services × 3 environments = 36 Applications from one ApplicationSet; onboarding a service is "add a directory".
- A new regional cluster is registered with label
env=prod: it receives every prod app with no YAML change. - Preview environments per pull request labelled
preview, deleted when the PR closes. - Cluster bootstrapping: a root Application syncs
argocd/, which holds the projects and ApplicationSets.
| Generator | Parameters from | Typical use |
|---|---|---|
| List | Literal elements | A fixed handful of clusters or tenants |
| Cluster | Argo CD cluster Secrets (labels) | "Every prod cluster gets the add-ons" |
| Git (directories / files) | Repo layout or JSON/YAML files | One Application per overlay directory |
| Matrix | Product of two children | Apps × clusters |
| Merge | Base generator overridden by others | Per-cluster overrides of defaults |
| Pull Request | Open PRs (GitHub, GitLab, Gitea, Bitbucket ...) | Preview environments |
| SCM Provider | Repositories of an org | One app per repository |
Fix: the shop ApplicationSet, the preview ApplicationSet and the root app:
# One ApplicationSet generates an <app>-<env> Application per overlay directory.
# Matrix of two children: the git directory generator discovers apps/*/overlays/* in the
# config repo; the cluster generator then picks the Argo CD cluster whose Secret carries
# the label env=<overlay name>. A new overlay or a new labelled cluster needs no new YAML.
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: shop
namespace: argocd
spec:
goTemplate: true
goTemplateOptions: ["missingkey=error"]
generators:
- matrix:
generators:
# child 1 produces path.path, path.basename and path.segments
- git:
repoURL: https://github.com/acme/shop-config.git
revision: main
directories:
- path: apps/*/overlays/*
# child 2 consumes child 1's parameters (it must come second). The selector never
# matches the default local cluster (it has no Secret): see cluster-staging.yaml
- clusters:
selector:
matchLabels:
argocd.argoproj.io/secret-type: cluster
env: '{{.path.basename}}'
# let on-call disable auto-sync on ONE generated Application during an incident:
# without this rule the controller resets spec.syncPolicy to the template's value
ignoreApplicationDifferences:
- jsonPointers:
- /spec/syncPolicy
template:
metadata:
# path.segments is [apps, <app>, overlays, <env>]
name: '{{index .path.segments 1}}-{{.path.basename}}'
annotations:
notifications.argoproj.io/subscribe.on-sync-failed.slack: shop-deploys
notifications.argoproj.io/subscribe.on-health-degraded.slack: shop-deploys
spec:
project: shop
source:
repoURL: https://github.com/acme/shop-config.git
targetRevision: main
path: '{{.path.path}}'
destination:
server: '{{.server}}'
namespace: 'shop-{{.path.basename}}'
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- ServerSideApply=true
- PruneLast=true
ignoreDifferences:
- group: apps
kind: Deployment
jsonPointers:
- /spec/replicas# Preview environments: one Application per open pull request labelled "preview" in the
# orders-api application repository. CI pushes an image tagged with the PR head SHA;
# the Application renders the preview overlay with that tag in its own namespace.
# Closing or merging the PR deletes the Application (and, through the finalizer, the env).
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: orders-api-previews
namespace: argocd
spec:
goTemplate: true
goTemplateOptions: ["missingkey=error"]
generators:
- pullRequest:
github:
owner: acme
repo: orders-api
tokenRef:
secretName: github-token
key: token
labels:
- preview
# without the ApplicationSet webhook, new PRs are found by polling (default 30 min)
requeueAfterSeconds: 300
template:
metadata:
name: 'orders-api-pr-{{.number}}'
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
# a fixed project (never templated from PR data) keeps a PR from widening its rights
project: shop-previews
source:
repoURL: https://github.com/acme/shop-config.git
targetRevision: main
# the preview overlay sets no namespace; kustomize.namespace puts every object in
# the PR namespace (destination.namespace alone only fills objects that have none)
path: apps/orders-api/overlays/preview
kustomize:
namespace: 'orders-api-pr-{{.number}}'
images:
- 'ghcr.io/acme/orders-api:pr-{{.head_short_sha}}'
destination:
server: https://kubernetes.default.svc
namespace: 'orders-api-pr-{{.number}}'
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true# App of apps: the only Application created by hand (or by the bootstrap script).
# It syncs the argocd/ directory, which holds the AppProject, the ApplicationSets and
# the per-app Applications. Admin-only: whoever can push here can create Applications
# in any project, so the directory is protected by CODEOWNERS and branch protection.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: root
namespace: argocd
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: platform
source:
repoURL: https://github.com/acme/shop-config.git
targetRevision: main
path: argocd
directory:
recurse: true
# excluded: the ConfigMaps (applied with the Argo CD installation itself) and the
# standalone orders-api-prod Application, which only illustrates what the shop
# ApplicationSet generates (applying both would create the same Application twice)
exclude: '{argocd-cm*.yaml,argocd-*-cm.yaml,app-orders-api-prod.yaml}'
destination:
server: https://kubernetes.default.svc
namespace: argocd
syncPolicy:
automated:
prune: true
selfHeal: trueThe cluster generator's selector matches only clusters that have a Secret; "the default local cluster does not have a Secret", so the local cluster is declared explicitly with the env label:
# The local cluster declared as a cluster Secret so it can carry the env label.
# A selector on argocd.argoproj.io/secret-type never matches the default local cluster
# (it has no Secret), so without this the shop ApplicationSet would generate no
# staging Applications. The prod cluster is registered the same way (with credentials,
# kept out of Git: SOPS, Sealed Secrets or ESO) and labelled env: prod.
apiVersion: v1
kind: Secret
metadata:
name: cluster-staging
namespace: argocd
labels:
argocd.argoproj.io/secret-type: cluster
env: staging
stringData:
name: staging
server: https://kubernetes.default.svc
config: '{"tlsClientConfig":{"insecure":false}}'Argo CD RBAC, SSO and Argo CD Notifications Important
In plain words: People log in through your identity provider; Casbin-style rules say who may sync or roll back which apps; notifications tell Slack (or email, PagerDuty, GitHub) when something happens.
Common misunderstanding: "Argo CD RBAC replaces Kubernetes RBAC." It controls what users do through Argo CD; the application-controller itself applies with its own ServiceAccount, whose Kubernetes rights bound what any Application can do (see Kubernetes Security).
Definition: SSO: "There are two ways that SSO can be configured": the bundled Dex OIDC provider (for SAML, LDAP or GitHub org/team mapping) or an existing OIDC provider via oidc.config in argocd-cm. The built-in admin user should be used "only for initial configuration and then switch to local users or configure SSO integration" (admin.enabled: "false"). Argo CD RBAC lives in argocd-rbac-cm: policy.default (e.g. role:readonly), scopes (which token claims are groups), and policy.csv with p, <role/user/group>, <resource>, <action>, <object>, <effect> and g, <user/group>, <role>; built-in roles are role:readonly and role:admin. Argo CD Notifications reads argocd-notifications-cm: service.<name>, template.<name>, trigger.<name> (a when expression and the templates to send); Applications subscribe with notifications.argoproj.io/subscribe.<trigger>.<service>: <recipient>. The catalog includes on-created, on-deleted, on-deployed, on-health-degraded, on-sync-failed, on-sync-running, on-sync-status-unknown, on-sync-succeeded.
Developer clicks "Sync" on orders-api-prod
1 browser -> argocd-server, OIDC token with groups [acme:shop-developers]
2 g, acme:shop-developers, role:shop-dev -> role:shop-dev
3 p, role:shop-dev, applications, sync, shop/*-staging, allow -> no match for shop/orders-api-prod
4 policy.default role:readonly -> sync denied (permission denied)
5 release manager (acme:shop-release-managers) -> role:shop-release -> allowed, inside the sync windowReal scenarios:
- Developers may sync and roll back staging; only release managers touch prod; platform admins are
role:admin. - A failed prod sync posts to
#shop-deployswith the revision and the operation message. - A GitHub commit status per sync (
github-commit-statustemplate in the docs' triggers example) shows deploy state on the commit.
| File | Holds |
|---|---|
argocd-cm | url, oidc.config or dex.config, admin.enabled, timeout.reconciliation, tracking method, resource customizations |
argocd-rbac-cm | policy.default, policy.csv, scopes |
argocd-notifications-cm | services, templates, triggers, context |
argocd-secret / labelled Secrets | client secrets, tokens (referenced as $key) |
Fix:
# Argo CD RBAC (Casbin syntax). SSO groups come from the OIDC "groups" claim.
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-rbac-cm
namespace: argocd
data:
# everyone who logs in can look, nobody can change anything by default
policy.default: role:readonly
scopes: '[groups]'
policy.csv: |
# developers: sync and roll back staging apps of the shop project, read everything
p, role:shop-dev, applications, get, shop/*, allow
p, role:shop-dev, applications, sync, shop/*-staging, allow
p, role:shop-dev, applications, rollback, shop/*-staging, allow
p, role:shop-dev, logs, get, shop/*, allow
# release managers: prod sync and rollback; still no create/delete of Applications
p, role:shop-release, applications, sync, shop/*-prod, allow
p, role:shop-release, applications, rollback, shop/*-prod, allow
g, role:shop-release, role:shop-dev
# map SSO groups to roles
g, acme:shop-developers, role:shop-dev
g, acme:shop-release-managers, role:shop-release
g, acme:platform-admins, role:admin# Argo CD Notifications: a Slack service, one template and two triggers from the catalog.
# Applications subscribe with annotations such as
# notifications.argoproj.io/subscribe.on-sync-failed.slack: shop-deploys
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-notifications-cm
namespace: argocd
data:
service.slack: |
token: $slack-token
context: |
argocdUrl: https://argocd.acme.internal
template.app-sync-failed: |
message: |
{{.app.metadata.name}} failed to sync revision {{.app.status.operationState.syncResult.revision}}:
{{.app.status.operationState.message}}
{{.context.argocdUrl}}/applications/{{.app.metadata.name}}
template.app-health-degraded: |
message: |
{{.app.metadata.name}} is {{.app.status.health.status}}.
{{.context.argocdUrl}}/applications/{{.app.metadata.name}}
trigger.on-sync-failed: |
- when: app.status?.operationState.phase in ['Error', 'Failed']
send: [app-sync-failed]
trigger.on-health-degraded: |
- when: app.status.health.status == 'Degraded'
send: [app-health-degraded]# argocd-cm (excerpt): the knobs this chapter discusses.
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-cm
namespace: argocd
data:
url: https://argocd.acme.internal
# poll Git every 120s plus up to 60s jitter (the defaults); webhooks make it instant
timeout.reconciliation: 120s
timeout.reconciliation.jitter: 60s
# annotation tracking (the default in Argo CD 3.x): argocd.argoproj.io/tracking-id
application.resourceTrackingMethod: annotation
# SSO through an existing OIDC provider (the bundled Dex is the other option)
oidc.config: |
name: Acme SSO
issuer: https://sso.acme.internal/realms/acme
clientID: argocd
clientSecret: $oidc.acme.clientSecret
requestedScopes: ["openid", "profile", "email", "groups"]
# disable the built-in admin user once SSO works
admin.enabled: "false"Argo CD Image Updater Important
In plain words: A separate controller watches your registry and, when a newer allowed tag appears, tells Argo CD to use it, ideally by committing the tag to Git.
Common misunderstanding: "Image Updater writes to Git by default." The default write-back method is argocd, which "directly modifies the Argo CD Application resource" and "is pseudo-persistent. If you delete the Application resource from the cluster and re-create it, changes made by Image Updater will be gone." For GitOps use the git method.
Definition: Argo CD Image Updater "can check for new versions of the container images that are deployed with your Kubernetes workloads and automatically update them to their latest allowed version using Argo CD". Since v1.0.0 it is configured with the ImageUpdater custom resource (argocd-image-updater.argoproj.io/v1alpha1): applicationRefs[].namePattern, images[].imageName with a version constraint, commonUpdateSettings.updateStrategy (semver, newest-build — renamed from latest — alphabetical, digest, calver), manifestTargets.kustomize.name or .helm.name, and writeBackConfig.method (argocd or git, git:secret:<ns>/<name> for credentials) with gitConfig.branch and gitConfig.writeBackTarget (default .argocd-source-<appName>.yaml; kustomization commits "as though you ran kustomize edit set image"; helmvalues:<path>). Limitations by design: only Argo CD-managed apps, and only those rendered with Kustomize, Helm or a config management plugin.
orders-api 1.5.1 pushed to ghcr.io
1 Image Updater reconcile: list tags of ghcr.io/acme/orders-api, constraint 1.x, strategy semver -> 1.5.1
2 app orders-api-staging currently renders 1.5.0 -> update needed
3 git write-back: clone shop-config, checkout main, edit apps/orders-api/overlays/staging/kustomization.yaml
4 commit + push (as the configured Git user)
5 Argo CD sees the new commit -> automated sync -> staging runs 1.5.1Real scenarios:
- Staging always runs the newest 1.x build without a human; prod is promoted by PR.
- A team uses
newest-buildonmain-*tags for a dev cluster;semvereverywhere else. - Tracking
HEADor a tag in the Application breaks Git write-back unlessgitConfig.branchis set ("your application really should track a branch").
| Need | Image Updater | Flux image automation |
|---|---|---|
| Install | Separate project/controller | --components-extra=image-reflector-controller,image-automation-controller |
| Config | ImageUpdater CR | ImageRepository + ImagePolicy + ImageUpdateAutomation |
| Where the tag goes | Application params, .argocd-source-<app>.yaml, kustomization or Helm values | Any YAML field with a $imagepolicy marker |
| PR flow | gitConfig.branch: "base:target" writes to another branch | git.push.branch different from checkout branch |
Fix:
# Argo CD Image Updater (v1.x, CRD-based): watch the registry for new orders-api tags
# within 1.x and commit the newest one to the staging overlay's kustomization.yaml.
# The git write-back method makes the change persistent; the default "argocd" method
# only patches the Application object in the cluster.
apiVersion: argocd-image-updater.argoproj.io/v1alpha1
kind: ImageUpdater
metadata:
name: orders-api-staging
namespace: argocd
spec:
writeBackConfig:
method: "git:secret:argocd/git-creds"
gitConfig:
branch: main
writeBackTarget: "kustomization"
applicationRefs:
- namePattern: "orders-api-staging"
images:
- alias: "orders-api"
imageName: "ghcr.io/acme/orders-api:1.x"
commonUpdateSettings:
updateStrategy: "semver"
manifestTargets:
kustomize:
name: "ghcr.io/acme/orders-api"Flux controllers: source-controller, kustomize-controller, helm-controller, notification-controller, image-reflector-controller, image-automation-controller Must-know
In plain words: Flux is a set of small controllers. One fetches things, two apply things, one sends and receives events, two automate image updates.
Common misunderstanding: "Installing Flux gives me image automation." The image controllers "are not installed by default"; add them with --components-extra.
Definition: source-controller's "main role ... is to provide a common interface for artifacts acquisition": authenticate, detect changes ("semver"), package as tar.gz, make artifacts addressable and available in-cluster, notify consumers. kustomize-controller reconciles cluster state from sources, "Generates manifests with Kustomize", "Decrypts Kubernetes secrets with Mozilla SOPS and KMS", "Impersonates service accounts (multi-tenancy RBAC)", "Runs pipelines in a specific order (depends-on relationship)" and "Prunes objects removed from source (garbage collection)". helm-controller turns HelmRelease objects into real Helm actions "including Helm tests, rollbacks and uninstalls" with automated remediation. notification-controller handles "inbound and outbound events": webhooks from GitHub, GitLab, Harbor and others in, events to Slack, Teams, Discord and others out. image-reflector-controller "scans image repositories and reflects the image metadata"; image-automation-controller "updates YAML files based on the latest images scanned, and commits" them. Together they are the GitOps Toolkit.
flux bootstrap github ... --path=clusters/staging (expected, not run)
1 install controllers into flux-system (gotk-components.yaml)
2 create GitRepository flux-system (this repo) + Kustomization flux-system (path clusters/staging)
3 push gotk-components.yaml and gotk-sync.yaml to the repo
4 from now on: source-controller fetches clusters/staging, kustomize-controller applies it,
including infrastructure.yaml and apps.yaml, which define further KustomizationsReal scenarios:
- Upgrading Flux is a commit that changes
gotk-components.yaml; Flux upgrades itself ("Flux can manage itself just as it manages other resources"). kubectl get fluxcd -Alists every Flux object across CRD types.- A team without image automation needs never runs the two image controllers.
| Controller | CRDs | Installed by default |
|---|---|---|
| source-controller | GitRepository, OCIRepository, HelmRepository, HelmChart, Bucket | Yes |
| kustomize-controller | Kustomization | Yes |
| helm-controller | HelmRelease | Yes |
| notification-controller | Provider, Alert, Receiver | Yes |
| image-reflector-controller | ImageRepository, ImagePolicy | No (--components-extra) |
| image-automation-controller | ImageUpdateAutomation | No (--components-extra) |
| source-watcher | ArtifactGenerator | No (--components-extra) |
Fix: bootstrap once per cluster with the components you need; everything after that is Git.
Flux sources: GitRepository, OCIRepository and OCI artifacts Must-know
In plain words: A source object says where to fetch from, how often and which version; it produces an artifact other controllers consume.
Common misunderstanding: "OCI registries are only for images." flux push artifact "creates a tarball from the given directory or the single file and uploads the artifact to an OCI repository"; an OCIRepository pulls it like Git, and can verify a cosign signature.
Definition: "Sources produce an artifact that is consumed by other Flux components"; "The origin of the source is checked for changes on a defined interval". GitRepository: url, ref (branch, tag, semver, commit), interval, secretRef. OCIRepository: url: oci://..., ref (tag, semver, digest), layerSelector, and verify with provider: cosign (public keys, or keyless matchOIDCIdentity with issuer and subject regexes; on success the condition SourceVerified is True). In Flux's "Gitless GitOps" model "the Git server is no longer a production dependency, while the OCI registry becomes the unified source of truth for all configuration artifacts". Argo CD also "supports using OCI (Open Container Initiative) images as an application source" with repoURL: oci://....
Config as a signed OCI artifact (prod cluster)
1 merge to main -> CI: flux push artifact oci://ghcr.io/acme/shop-config:<sha> --path=. --source=... --revision=main@sha1:<sha>
2 CI: cosign sign --yes ghcr.io/acme/shop-config@sha256:... (keyless, workflow OIDC identity)
3 CI: flux tag artifact ...:<sha> --tag prod (overlays/prod itself only changes by reviewed PR)
4 prod OCIRepository (ref.tag prod) sees a new digest -> verify signature -> SourceVerified=True
5 Kustomization shop-laravel-prod applies ./apps/shop-laravel/overlays/prod from that artifactReal scenarios:
- Prod clusters in a restricted network can reach the registry mirror but not GitHub.
- Supply-chain policy: only config signed by the config repo's CI workflow may deploy.
- A Helm chart from
oci://ghcr.io/acme/charts/orders-apiwithref.semver: "1.3.x".
| Source | Use | Verify |
|---|---|---|
| GitRepository | Config repo, tenant repos | Commit signatures (PGP) via verify |
| OCIRepository | Config artifacts, Helm charts in OCI | cosign (keys or keyless), notation |
| HelmRepository | Classic HTTP Helm repos | Chart provenance in the chart workflow |
| Bucket | S3-compatible storage | Access control only |
Fix:
# Prod pulls the config as a signed OCI artifact instead of cloning Git ("Gitless"
# GitOps): the config repo's CI runs "flux push artifact" for each commit merged to main,
# signs it and moves the "prod" tag. Prod overlays change only through reviewed PRs.
# Git stays the interface for humans; the registry becomes the production dependency.
# (The staging cluster in this repository reads Git directly.)
apiVersion: source.toolkit.fluxcd.io/v1
kind: OCIRepository
metadata:
name: shop-config
namespace: flux-system
spec:
interval: 5m
url: oci://ghcr.io/acme/shop-config
ref:
tag: prod
# refuse artifacts that the config repo's CI workflow did not sign (keyless cosign)
verify:
provider: cosign
matchOIDCIdentity:
- issuer: "^https://token.actions.githubusercontent.com$"
subject: "^https://github.com/acme/shop-config.*$"
---
# The orders-api Helm chart, published by the service's own CI (see the Helm chapter)
apiVersion: source.toolkit.fluxcd.io/v1
kind: OCIRepository
metadata:
name: orders-api-chart
namespace: flux-system
spec:
interval: 10m
url: oci://ghcr.io/acme/charts/orders-api
ref:
semver: "1.3.x"Flux Kustomization: path, prune, interval, dependsOn, health checks, wait Must-know
In plain words: A Flux Kustomization says "apply this directory of that source, delete what disappears, check that it is healthy, and do it again every N minutes".
Common misunderstanding: "The Flux Kustomization is the kustomization.yaml file." Two different things with one name: kustomize.toolkit.fluxcd.io/v1 Kustomization is a CRD in the cluster; kustomize.config.k8s.io/v1beta1 Kustomization is the file Kustomize builds. The Flux object "represents a local set of Kubernetes resources (e.g. kustomize overlay) that Flux is supposed to reconcile".
Definition: Key fields: interval (required; reconcile, "correcting any existing drift in the process"), retryInterval, path, prune ("a required boolean field to enable/disable garbage collection"), sourceRef, targetNamespace (kustomize-controller "will not create the namespace automatically"), suspend ("drift detection/correction is paused"), healthChecks, wait ("perform health checks for all reconciled resources ... If set to true, .spec.healthChecks is ignored"), timeout, dependsOn ("only applied after the referred Kustomizations are ready"), serviceAccountName, decryption (SOPS), postBuild.substitute, force. Per-object annotations: kustomize.toolkit.fluxcd.io/ssa (Override, Merge, IfNotPresent, Ignore), .../force, .../prune: disabled, .../reconcile: disabled. The docs' example: "every ten minutes, the Kustomization runs a server-side apply dry-run to detect and correct drift inside the cluster."
Reconcile of shop-laravel-staging (interval 10m, wait: true, dependsOn infrastructure)
1 infrastructure Ready? no -> requeue (reason DependencyNotReady); yes -> continue
2 fetch artifact of GitRepository flux-system at main@sha1:9a1b...
3 kustomize build ./apps/shop-laravel/overlays/staging; decrypt SOPS Secrets
4 server-side apply dry-run -> changed objects -> apply; Jobs recreated (force: enabled)
5 prune objects from the previous inventory that are gone from this revision
6 wait: all Deployments rolled out, Jobs complete -> Ready=True "Applied revision: main@sha1:9a1b..."
failure -> Ready=False (BuildFailed / HealthCheckFailed / ...) -> Alert -> SlackReal scenarios:
- CRDs and controllers in an
infrastructureKustomization; appsdependsOnit. - A typo in
pathfails withkustomization path not found: stat /tmp/kustomization-.../invalid: no such file or directory(reasonArtifactFailed, from the docs). - During an incident,
flux suspend kustomization shop-laravel-prodstops drift correction while an engineer debugs live.
| Field | This chapter's value | Why |
|---|---|---|
interval | 10m apps, 1h infrastructure | Drift correction cadence; webhooks for speed |
retryInterval | 1m-2m | Faster retries after failure |
prune | true | Garbage collection of removed objects |
wait | true for shop-laravel | Ready means rolled out and Jobs done |
healthChecks | Deployment orders-api | Explicit list when wait is too broad |
dependsOn | infrastructure | Namespaces before apps |
decryption | sops / sops-age | Encrypted Secrets in Git |
timeout | 5m-10m | Bound for build, apply and health checks |
Fix: the Laravel Kustomization (the brief's "Laravel Kustomization") and the Go service's:
# Layer 2: the applications, applied only after "infrastructure" is Ready (dependsOn).
# Every 10 minutes kustomize-controller re-applies the overlay with a server-side
# dry-run diff, so a kubectl edit in shop-staging is reverted at the latest then.
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: orders-api-staging
namespace: flux-system
spec:
dependsOn:
- name: infrastructure
interval: 10m
retryInterval: 1m
timeout: 5m
path: ./apps/orders-api/overlays/staging
prune: true
sourceRef:
kind: GitRepository
name: flux-system
healthChecks:
- apiVersion: apps/v1
kind: Deployment
name: orders-api
namespace: shop-staging
---
# The Laravel app. wait: true health-checks every object it applied, including the
# migrate and smoke Jobs. Flux has no hook phases: both Jobs start in the same reconcile
# as the new Deployments. The smoke command polls the web Service until it serves the new
# version before checking anything else, so Ready=True means applied, rolled out, migrated
# and smoke-tested against the new pods.
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: shop-laravel-staging
namespace: flux-system
spec:
dependsOn:
- name: infrastructure
interval: 10m
retryInterval: 1m
timeout: 10m
path: ./apps/shop-laravel/overlays/staging
prune: true
wait: true
sourceRef:
kind: GitRepository
name: flux-system
# the env Secret is committed encrypted with SOPS (age); the controller decrypts it
decryption:
provider: sops
secretRef:
name: sops-age# Layer 1: cluster-wide objects (namespaces here; CRDs and controllers in real life).
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: infrastructure
namespace: flux-system
spec:
interval: 1h
retryInterval: 1m
timeout: 5m
path: ./infrastructure/namespaces
prune: true
wait: true
sourceRef:
kind: GitRepository
name: flux-system# The Laravel app in prod from the OCI artifact. Same overlay path, different source.
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: shop-laravel-prod
namespace: flux-system
spec:
dependsOn:
- name: infrastructure
interval: 10m
retryInterval: 2m
timeout: 10m
path: ./apps/shop-laravel/overlays/prod
prune: true
wait: true
sourceRef:
kind: OCIRepository
name: shop-config
decryption:
provider: sops
secretRef:
name: sops-ageHelmRelease: real Helm releases, remediation, drift detection Important
In plain words: A HelmRelease is "keep this chart at this version with these values installed", executed by a controller running real helm install/upgrade.
Common misunderstanding: "Argo CD and Flux treat Helm the same." Argo CD renders the chart and applies the output itself (no release in helm list); helm-controller performs Helm actions, so hooks, tests, release history and helm rollback semantics are Helm's.
Definition: chartRef (an OCIRepository or HelmChart; "One of .spec.chart or .spec.chartRef must be set, but not both"), releaseName, values / valuesFrom, install.remediation.retries, upgrade.remediation.retries, test.enable, and driftDetection: "When .spec.driftDetection.mode is set to warn or enabled ... the controller will compare the manifest from the Helm storage with the current state of the cluster using a server-side dry-run apply"; with enabled it "will attempt to correct the drift"; ignore takes JSON pointers ("useful when Horizontal Pod Autoscaling is enabled").
HelmRelease orders-api upgrade 1.4.2 -> 1.5.0 fails
1 helm-controller: upgrade -> pods never Ready -> timeout 5m -> upgrade failed
2 remediation retries 3: retry ... still failing -> RetriesExceeded
3 upgrade.remediation.strategy: rollback ("Defaults to rollback"; uninstall is the other value) restores the last release
4 Ready=False with the failure reason -> Alert -> Slack; Git still says 1.5.0 -> revert the commitReal scenarios:
- Third-party charts (ingress-nginx, cert-manager) as HelmReleases with values in Git.
- Drift detection catches someone deleting the chart's NetworkPolicy by hand.
- The Go service's chart from Packaging for Kubernetes delivered to prod.
| Concern | Flux HelmRelease | Argo CD with a Helm source |
|---|---|---|
helm list shows it | Yes | No |
| Helm hooks | Real Helm hooks | Mapped to Argo CD hooks |
| Failed upgrade | Remediation: retry, rollback, uninstall | Sync failed; retry policy |
| Drift | driftDetection.mode (warn / enabled) | selfHeal |
Fix:
# The Go service in prod as a HelmRelease: helm-controller runs a real Helm upgrade
# (the release shows in "helm list"), retries and rolls back on failure, and with
# driftDetection.mode=enabled corrects in-cluster edits against the stored release.
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: orders-api
namespace: shop-prod
spec:
interval: 15m
timeout: 5m
releaseName: orders-api
chartRef:
kind: OCIRepository
name: orders-api-chart
namespace: flux-system
install:
remediation:
retries: 3
upgrade:
remediation:
retries: 3
driftDetection:
mode: enabled
ignore:
# the HPA owns the replica count
- paths: ["/spec/replicas"]
target:
kind: Deployment
values:
image:
repository: ghcr.io/acme/orders-api
# the promote-to-prod workflow bumps tag and digest here in the same PR as
# apps/orders-api/overlays/prod (tag for humans, digest for the exact bytes)
tag: "1.4.2"
digest: sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3Flux notifications: Receiver, Alert and Provider Important
In plain words: A Receiver lets GitHub poke Flux the moment you push; an Alert plus a Provider sends Flux's events to Slack or sets commit statuses.
Common misunderstanding: "Without webhooks Flux is slow by design." Polling is the safety net; a Receiver makes delivery near-instant, and losing the webhook only costs one interval.
Definition: A Receiver (type: github, gitlab, generic, harbor ...; events; secretRef for the shared token; resources to reconcile) is served by the webhook-receiver Service at the path published in .status.webhookPath (/hook/<sha256>). A Provider is a destination (type: slack with channel, address, secretRef; type: github for "Git Commit Status Updates"; githubdispatch and many more). An Alert selects eventSources (kind, name, namespace), eventSeverity (info or error) and adds eventMetadata.
git push -> GitHub webhook -> https://flux-webhook.acme.internal/hook/bed6d0...
1 notification-controller validates the token, matches Receiver github-shop-config
2 annotates GitRepository flux-system to reconcile now -> source-controller fetches
3 Kustomizations depending on it reconcile -> events (info/error)
4 Alert shop-errors (severity error) -> Provider slack -> #shop-deploys
5 Alert shop-commit-status -> Provider github -> commit status on the config repoReal scenarios:
- Deploy latency drops from "up to 10 minutes" to seconds.
- The config repo's commit page shows whether staging reconciled the commit.
- Harbor sends push events to a Receiver that reconciles an ImageRepository.
| Object | Direction | Key fields |
|---|---|---|
| Receiver | In (webhooks) | type, events, secretRef, resources |
| Provider | Out (destination) | type, address, channel, secretRef |
| Alert | Out (routing) | providerRef, eventSources, eventSeverity, eventMetadata |
Fix:
# Outbound: errors from any Kustomization or HelmRelease go to Slack.
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Provider
metadata:
name: slack
namespace: flux-system
spec:
type: slack
channel: shop-deploys
address: https://slack.com/api/chat.postMessage
secretRef:
name: slack-bot-token
---
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Alert
metadata:
name: shop-errors
namespace: flux-system
spec:
providerRef:
name: slack
eventSeverity: error
eventMetadata:
env: staging
eventSources:
- kind: Kustomization
name: '*'
- kind: HelmRelease
name: '*'
---
# Outbound: commit statuses on the config repo (the commit shows whether it reconciled)
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Provider
metadata:
name: github-status
namespace: flux-system
spec:
type: github
address: https://github.com/acme/shop-config
secretRef:
name: github-status-token
---
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Alert
metadata:
name: shop-commit-status
namespace: flux-system
spec:
providerRef:
name: github-status
eventSeverity: info
eventSources:
- kind: Kustomization
name: shop-laravel-staging
---
# Inbound: GitHub push webhooks trigger an immediate fetch instead of waiting for
# the next interval. The URL path is published in .status.webhookPath (/hook/<sha256>).
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Receiver
metadata:
name: github-shop-config
namespace: flux-system
spec:
type: github
events:
- "ping"
- "push"
secretRef:
name: receiver-token
resources:
- apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
name: flux-systemFlux image automation: ImageRepository, ImagePolicy, ImageUpdateAutomation, write back to Git Must-know
In plain words: Flux scans the registry, picks the newest tag your policy allows, edits the marked lines in Git and commits. The normal GitOps loop then deploys the commit.
Common misunderstanding: "Image automation updates the Deployment in the cluster." It never touches the cluster: it writes back to Git, so the cluster only changes because Git changed and the audit trail stays complete.
Definition: ImageRepository (image, interval, secretRef) makes image-reflector-controller list tags. ImagePolicy (imageRepositoryRef, policy.semver.range / numerical / alphabetical, filterTags.pattern and extract, digestReflectionPolicy) selects one. Pre-releases need ranges such as ^1.x-0. ImageUpdateAutomation (sourceRef, git.checkout.ref.branch, git.commit.author and messageTemplate, git.push.branch, update.path, update.strategy: Setters) rewrites fields marked with # {"$imagepolicy": "<policy-namespace>:<policy-name>"} (full reference) or with the :tag, :name or :digest suffix. With push.branch different from the checkout branch, "If the specified branch doesn't exist, Flux will create it for you": the base of a PR-gated flow.
image automation of the Laravel tag, staging
1 CI pushes ghcr.io/acme/shop-app:2.9.0 (and sha-4f2a9c1)
2 ImageRepository shop-app scan: tags [2.7.0 2.8.1 2.9.0 sha-4f2a9c1 ...] (CI pushed shop-web:2.9.0 first)
3 ImagePolicy shop-laravel: filterTags ^[0-9]+\.[0-9]+\.[0-9]+$, semver >=2.0.0 <3.0.0 -> 2.9.0
4 ImageUpdateAutomation shop-laravel-staging: checkout main, path overlays/staging,
both lines newTag: "2.8.1" # {"$imagepolicy": "flux-system:shop-laravel:tag"} -> "2.9.0"
(shop-app and shop-web carry the SAME marker, so they change in the same commit)
5 commit "chore(staging): update shop-laravel images" by fluxcdbot, push main
6 Kustomization shop-laravel-staging: new revision -> apply Deployments + migrate and smoke Jobs together;
the smoke command polls shop-web /version until it serves 2.9.0, then checks DB, schema, cache
prod automation: same edit pushed to image-updates/shop-prod -> PR -> review -> merge -> prodReal scenarios:
- Staging follows every release automatically; prod gets a PR per release.
- CI also pushes
sha-<commit>tags;filterTagskeeps them out of the semver policy. - A typo in a marker's policy name means the field is never updated: this chapter's repository tests fail the PR.
- Two images that must move together (Laravel's php-fpm
shop-appand Nginxshop-web) get ONE ImagePolicy and the same marker on both lines; two independent policies can select 2.9.0 for one and still 2.8.1 for the other (this chapter'simagebumptest models exactly that and now asserts both lines change).
| Object | Controller | Answers |
|---|---|---|
| ImageRepository | image-reflector-controller | Which tags exist? |
| ImagePolicy | image-reflector-controller | Which tag is the latest allowed? |
| ImageUpdateAutomation | image-automation-controller | Which files, which branch, what commit message? |
$imagepolicy marker | (in your YAML) | Which field gets which value |
Fix: the policies and the two automations; the markers live in the overlays:
# Image automation for the Laravel images (installed with
# --components-extra=image-reflector-controller,image-automation-controller).
# 1. ImageRepository: image-reflector-controller lists the tags in the registry.
# 2. ImagePolicy: picks the newest tag inside the semver range.
# 3. ImageUpdateAutomation: image-automation-controller rewrites the marked fields
# in Git and pushes a commit; the Kustomization above then deploys it.
# One ImageRepository and ONE ImagePolicy for both Laravel images: CI releases shop-app
# and shop-web with the same version tag and pushes shop-web first, so a tag that exists
# for shop-app exists for shop-web. Both overlay lines carry the same marker and change
# in one commit; two independent policies could leave app 2.9.0 next to web 2.8.1.
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImageRepository
metadata:
name: shop-app
namespace: flux-system
spec:
image: ghcr.io/acme/shop-app
interval: 5m
secretRef:
name: ghcr-read
---
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImagePolicy
metadata:
name: shop-laravel
namespace: flux-system
spec:
imageRepositoryRef:
name: shop-app
# only release tags like 2.8.1 (CI also pushes sha-<commit> tags, which are ignored)
filterTags:
pattern: '^[0-9]+\.[0-9]+\.[0-9]+$'
policy:
semver:
range: '>=2.0.0 <3.0.0'
---
# staging: commit straight to main
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImageUpdateAutomation
metadata:
name: shop-laravel-staging
namespace: flux-system
spec:
interval: 10m
sourceRef:
kind: GitRepository
name: flux-system
git:
checkout:
ref:
branch: main
commit:
author:
name: fluxcdbot
email: fluxcdbot@users.noreply.github.com
messageTemplate: |-
chore(staging): update shop-laravel images
{{ .Changed.Summary }}
push:
branch: main
update:
path: ./apps/shop-laravel/overlays/staging
strategy: Setters
---
# prod: same policies, but push to a separate branch; a pull request from
# image-updates/shop-prod to main is the human approval step
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImageUpdateAutomation
metadata:
name: shop-laravel-prod
namespace: flux-system
spec:
interval: 30m
sourceRef:
kind: GitRepository
name: flux-system
git:
checkout:
ref:
branch: main
commit:
author:
name: fluxcdbot
email: fluxcdbot@users.noreply.github.com
messageTemplate: |-
chore(prod): promote shop-laravel images
{{ .Changed.Summary }}
push:
branch: image-updates/shop-prod
update:
path: ./apps/shop-laravel/overlays/prod
strategy: Setters# staging: Flux image automation owns the two tags below. Both carry the marker of the
# single shop-laravel ImagePolicy, so image-automation-controller rewrites them together
# in one commit to main.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-staging
resources:
- ../../base
- ../../release-jobs
labels:
- pairs:
app.kubernetes.io/environment: staging
images:
- name: ghcr.io/acme/shop-app
newTag: "2.8.1" # {"$imagepolicy": "flux-system:shop-laravel:tag"}
- name: ghcr.io/acme/shop-web
newTag: "2.8.1" # {"$imagepolicy": "flux-system:shop-laravel:tag"}
replicas:
- name: shop-web
count: 1
- name: shop-worker
count: 1flux bootstrap and multi-tenancy Important
In plain words: Bootstrap installs Flux and commits Flux's own manifests to your repo so Flux manages itself. Multi-tenancy makes each team's Flux objects run with that team's permissions only.
Common misunderstanding: "Flux applies everything as cluster-admin, so tenants can do anything." By default the controllers' own ServiceAccount is used; with the lockdown flags, a tenant's Kustomization without serviceAccountName falls back to a namespace-local default account and cannot touch other namespaces.
Definition: flux bootstrap github "deploys the Flux controllers on a Kubernetes cluster and configures the controllers to sync the cluster state from a GitHub repository", pushes the Flux manifests and "configures Flux to update itself from Git"; after that "any operation on the cluster (including Flux upgrades) can be done via Git push". The person bootstrapping needs cluster-admin and repository admin rights; the PAT (with --token-auth) is stored as the flux-system Secret. Multi-tenancy: platform admins bootstrap, add CRDs and controllers, "Set up namespaces for tenants and define their level of access with Kubernetes RBAC" and onboard tenant repositories; tenants register sources and deploy "into their namespace(s)". Lockdown patches add --no-cross-namespace-refs=true (most controllers), --no-remote-bases=true (kustomize-controller) and --default-service-account=default (kustomize-controller, helm-controller, source-watcher).
Tenant team-orders pushes a manifest for namespace payments (expected, not run)
1 Kustomization team-orders (serviceAccountName team-orders-reconciler, targetNamespace team-orders)
2 kustomize-controller impersonates system:serviceaccount:team-orders:team-orders-reconciler
3 apply in team-orders: allowed (RoleBinding to ClusterRole admin, namespaced)
4 targetNamespace rewrites everything into team-orders; a ClusterRole in the tenant repo -> forbidden
5 Ready=False with the API server's forbidden message -> the tenant fixes their repoReal scenarios:
- A platform team runs one cluster for eight product teams, each with its own deploy repo.
--no-remote-bases=truestops a tenant from pulling unreviewed manifests from the internet at every reconcile.- Rotating the deploy key: delete the
flux-systemSecret and rerun bootstrap.
| Flag / field | Effect |
|---|---|
--components-extra=image-reflector-controller,image-automation-controller | Installs image automation |
--path=clusters/<name> | The directory this cluster syncs |
--read-write-key | Deploy key with write access (needed for image automation) |
serviceAccountName | Impersonation per Kustomization/HelmRelease |
--no-cross-namespace-refs=true | Tenants cannot reference sources in other namespaces |
--default-service-account=default | Objects without serviceAccountName get a namespace-local identity |
Fix:
# Flux multi-tenancy: the platform team onboards the orders team. Their own repository
# is reconciled under a namespaced ServiceAccount, so a tenant manifest that targets
# another namespace or a cluster-scoped kind is rejected by Kubernetes RBAC.
# (Lockdown flags on the controllers: --no-cross-namespace-refs=true,
# --default-service-account=default, --no-remote-bases=true.)
apiVersion: v1
kind: Namespace
metadata:
name: team-orders
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: team-orders-reconciler
namespace: team-orders
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: team-orders-reconciler
namespace: team-orders
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
# the built-in "admin" ClusterRole bound by a RoleBinding: admin of this namespace only
name: admin
subjects:
- kind: ServiceAccount
name: team-orders-reconciler
namespace: team-orders
---
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: team-orders
namespace: team-orders
spec:
interval: 5m
url: https://github.com/acme/team-orders-deploy
ref:
branch: main
secretRef:
name: team-orders-git
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: team-orders
namespace: team-orders
spec:
serviceAccountName: team-orders-reconciler
targetNamespace: team-orders
interval: 10m
path: ./deploy
prune: true
sourceRef:
kind: GitRepository
name: team-ordersDrift detection, self-heal and manual changes reverted Must-know
In plain words: Drift is any difference between Git and the cluster that nobody committed. Self-heal is the agent undoing it. Sometimes you want it undone at once, sometimes you need it to stay for an hour.
Common misunderstanding: "Self-heal makes kubectl edit impossible, so it must be off during incidents." The better incident move is explicit: suspend reconciliation for that app (Flux flux suspend kustomization, or kustomize.toolkit.fluxcd.io/reconcile: disabled on one object; Argo CD: disable automated sync on that Application, which for an ApplicationSet-generated Application only sticks if the ApplicationSet has ignoreApplicationDifferences on /spec/syncPolicy), change live, then commit the fix and resume.
Definition: Drift detection is the comparison step of every reconcile. Argo CD reports OutOfSync and, with selfHeal: true, re-syncs after the self-heal timeout. Flux's concepts page: "If you make any changes to the cluster using kubectl edit/patch/delete, they will be promptly reverted. You either suspend the reconciliation or push your changes to a Git repository." Flux's FAQ adds that "fields specified in Git will always be overridden" and that only new fields added with field manager flux-client-side-apply survive (for example kubectl --field-manager=flux-client-side-apply rollout restart). HelmReleases correct drift only with driftDetection.mode: enabled.
02:00 incident: orders-api leaking memory; on-call scales it up by hand
1 kubectl scale deploy/orders-api --replicas=12 -n shop-prod
2a Argo CD, selfHeal on, Git sets replicas -> back to the Git value within seconds; on-call confused
2b Flux Kustomization -> back to Git at the next interval (<= 10m)
3 right way: suspend first, act, open PR
Flux: flux suspend kustomization orders-api-prod
Argo CD: set spec.syncPolicy.automated.enabled: false on the Application. For an ApplicationSet-generated
app, "changing the application's spec.syncPolicy.automated field will, however, have no effect"
unless the ApplicationSet ignores it: ignoreApplicationDifferences: [{jsonPointers: [/spec/syncPolicy]}]
(set in appset-shop.yaml); otherwise pause at the ApplicationSet (template or applicationsSync policy)
4 after the fix is merged: resume; the agent and Git agree againReal scenarios:
- A developer "temporarily" sets
LOG_LEVEL=debugwithkubectl set env; GitOps reverts it before it fills the disks. - An attacker with stolen credentials modifies a Deployment's image: self-heal restores it and the OutOfSync event is evidence.
- A load test needs replicas pinned for an hour: suspend the app, or commit the change to a branch overlay.
| When | Self-heal / drift correction | Why |
|---|---|---|
| Production, no manual access | On | Git is the only truth; drift is an incident |
| Shared dev clusters | On, but with fast PR path | Prevent snowflakes |
| Active incident on that app | Suspend that app only | Humans must not race the agent |
| Fields owned by controllers (HPA, mesh) | On, with ignore rules | Otherwise the agent and controller flap |
| Migration from push-based deploys | Off for a week, watch OutOfSync | Find hidden manual changes before reverting them |
Fix: turn self-heal on everywhere it can be on, alert on OutOfSync that lasts more than a few minutes, and write the suspend/resume steps into the runbook. The Go drift model shows why server-defaulted fields are not drift and why ignore rules exist.
Secrets in GitOps: SOPS, Sealed Secrets, ESO Important
In plain words: Never commit plain Secrets. Commit encrypted ones (SOPS, Sealed Secrets) or commit a pointer to a secret manager (External Secrets Operator).
Common misunderstanding: "A private repository is safe enough." Flux: "Storing Secrets in Git repositories in plain text or base64 is unsafe, regardless of the visibility or access restrictions of the repository."
Definition: Three patterns, all owned by Kubernetes Config, Secrets & Storage: SOPS link — SOPS "is an editor of encrypted files that supports YAML, JSON, ENV, INI and BINARY formats and encrypts with AWS KMS, GCP KMS, Azure Key Vault, HuaweiCloud KMS, age, and PGP"; kustomize-controller decrypts with spec.decryption.provider: sops ("The only supported encryption provider is SOPS"); Argo CD has no built-in SOPS step, so Argo CD setups usually add a config management plugin or prefer ESO. Sealed Secrets link — a controller-held key decrypts SealedSecret objects in the cluster; the Argo CD declarative docs even suggest it for repository credentials. ESO link — the External Secrets Operator syncs from Vault, AWS Secrets Manager and others; Git only holds the ExternalSecret. Details and trade-offs: GitOps secrets and ESO.
SOPS with Flux (expected, not run)
1 sops --encrypt --age age1... secret.yaml > secret.enc.yaml ; commit secret.enc.yaml
2 kustomize-controller: build overlay, find SOPS-encrypted Secret, decrypt with key from Secret sops-age
3 apply the plain Secret to the cluster; Git only ever saw ciphertextReal scenarios: the Laravel shop-laravel-env Secret (APP_KEY, DB password) as SOPS in Git for Flux, or as an ExternalSecret for Argo CD; registry credentials for ImageRepository secretRef; the notifications Slack token in argocd-notifications-secret.
| Pattern | Agent support | Key lives |
|---|---|---|
| SOPS | Flux built in; Argo CD via plugin | KMS / age key in the cluster |
| Sealed Secrets | Both (it is just a CR) | Controller key in the cluster |
| External Secrets Operator | Both (it is just a CR) | External secret manager |
Fix: pick one per platform; this chapter's Flux Kustomizations use SOPS (decryption above).
Environment promotion: image tag bump PR, Kargo Must-know
In plain words: Promotion is copying "the version that passed staging" into prod's desired state. In GitOps that is a commit, ideally a reviewed pull request.
Common misunderstanding: "Promotion means merging the staging branch into prod." With directories per environment, promotion is a small diff in overlays/prod (tag and digest), not a branch merge that drags along everything else.
Definition: Environment promotion moves a known-good artifact version through stages. Common mechanisms: an image tag bump PR opened by CI, a bot or Flux image automation pushing to a separate branch; Argo CD Image Updater with gitConfig.branch: "base:target"; or Kargo, "an unopinionated continuous promotion platform" whose docs draw the line: "Promotions are different from deployments ... The job of deploying ... is left to a GitOps agent like Argo CD." Kargo's terms: Warehouse (watches repositories and packages new revisions), Freight ("a 'meta-artifact' that references specific revisions of artifacts like images and manifests"), Stage ("a promotion target"), Promotion, Project.
orders-api 1.5.0 from staging to prod
1 staging runs 1.5.0 (Image Updater commit), Healthy for 24 h, PostSync smoke ok
2 release manager runs workflow promote-to-prod (app=orders-api, tag=1.5.0, digest=sha256:...)
3 imagebump edits apps/orders-api/overlays/prod/kustomization.yaml (Argo CD's source) AND
clusters/prod/helmrelease-orders-api.yaml values.image (Flux's source): 2 lines each, one PR
4 PR "promote(prod): orders-api 1.5.0" -> CODEOWNERS review, config-repo checks green -> merge
5 Argo CD (prod) syncs inside the allowed sync window -> HealthyReal scenarios:
- Several artifacts must move together (an image plus a config change): Kargo Freight bundles them.
- Regulated prod: the PR approval is the change record.
- Staging gets every patch; prod gets one PR per week bundling the tested tag.
| Mechanism | Who writes the commit | Gate |
|---|---|---|
| CI opens a PR (this chapter's workflow) | CI bot | PR review |
| Flux image automation to a branch | image-automation-controller | PR review |
Argo CD Image Updater base:target branch | Image Updater | PR review |
| Kargo Promotion | Kargo (steps: git commit, PR, Argo CD update) | Stage verification, manual or auto |
| Direct commit to main | Anyone with push | None: avoid for prod |
Fix: the promotion workflow and the tool it runs. Every file that names the prod version is bumped in the same PR; a promotion that edits only the overlay would leave the Flux HelmRelease (which carries its own values.image) on the old version:
# Promotion = a pull request. A release manager runs this workflow with the tag that
# passed staging; it rewrites EVERY file that names the prod version (the prod overlay
# that Argo CD renders and, when the app is also delivered by a Flux HelmRelease, that
# HelmRelease's values.image) and opens one PR. Merging it is the deployment approval.
name: promote-to-prod
on:
workflow_dispatch:
inputs:
app:
description: "App directory under apps/ (orders-api or shop-laravel)"
required: true
image:
description: "Image repository, e.g. ghcr.io/acme/orders-api"
required: true
tag:
description: "Tag that passed staging, e.g. 1.5.0"
required: true
digest:
description: "Digest CI printed for that tag (sha256:...)"
required: true
permissions:
contents: write
pull-requests: write
jobs:
open-pr:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: tools/go.mod
- name: Bump the prod overlay and the prod HelmRelease
working-directory: tools
run: |
set -euo pipefail
go run ./cmd/imagebump \
-file "../apps/${{ inputs.app }}/overlays/prod/kustomization.yaml" \
-image "${{ inputs.image }}" -tag "${{ inputs.tag }}" -digest "${{ inputs.digest }}"
hr="../clusters/prod/helmrelease-${{ inputs.app }}.yaml"
if [ -f "$hr" ]; then
go run ./cmd/imagebump -format helm -file "$hr" \
-image "${{ inputs.image }}" -tag "${{ inputs.tag }}" -digest "${{ inputs.digest }}"
fi
- name: Open the promotion pull request
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: promote/${{ inputs.app }}-${{ inputs.tag }}
run: |
set -euo pipefail
git config user.name "release-bot"
git config user.email "release-bot@users.noreply.github.com"
git switch -c "$BRANCH"
git commit -am "promote(prod): ${{ inputs.app }} ${{ inputs.tag }}"
git push origin "$BRANCH"
gh pr create --base main --head "$BRANCH" \
--title "promote(prod): ${{ inputs.app }} ${{ inputs.tag }}" \
--body "Tag ${{ inputs.tag }} (${{ inputs.digest }}) passed staging."Rollback by revert vs argocd app rollback Must-know
In plain words: Roll back by reverting the commit that broke things. Argo CD's rollback button exists, but it makes the cluster disagree with Git.
Common misunderstanding: "argocd app rollback is the GitOps rollback." It re-syncs an old revision from the Application's history, and "Rollback cannot be performed against an application with automated sync enabled": you must disable auto-sync first, after which the cluster runs something Git does not say.
Definition: Rollback by revert: git revert <sha> creates a new commit restoring the previous desired state; the agent syncs it like any change; history stays linear and auditable. argocd app rollback APPNAME [ID]: "Rollback application to a previous deployed version by History ID, omitted will Rollback to the previous version" (--prune allowed); history length is spec.revisionHistoryLimit. Flux has no rollback command; helm-controller's remediation can roll back a failed Helm upgrade, but Git still names the new version until you revert.
1.5.0 broke prod at 14:02
revert path rollback-button path
1 git revert 3e9d (promotion commit) 1 disable automated sync on orders-api-prod (needs the ignoreApplicationDifferences rule: generated app)
2 PR (fast-track approval) -> merge 2 argocd app rollback orders-api-prod 41
3 agent syncs 1.4.2 3 cluster runs 1.4.2, Git says 1.5.0 (OutOfSync)
4 Git == cluster, audit trail intact 4 must still revert Git, then re-enable auto-syncReal scenarios:
- Image-only regressions: revert the promotion commit (two lines).
- A migration already ran: reverting the image does not undo the schema; backwards-compatible (expand/contract) migrations are what make image rollbacks safe.
- A bad chart upgrade under Flux: helm-controller remediation rolls back the release; the follow-up revert keeps it there.
| Method | Git agrees afterwards | Works with auto-sync | Audit |
|---|---|---|---|
git revert + sync | Yes | Yes | Commit + PR |
argocd app rollback | No | No (must disable) | Argo CD history only |
| Flux HelmRelease remediation | No (until revert) | Yes | Events |
kubectl rollout undo | No (reverted by self-heal) | Fights the agent | None |
Fix: keep a "revert the last promotion" runbook step and allow fast-track approval for revert PRs.
Progressive delivery: Argo Rollouts link, Flagger link Good to know
In plain words: GitOps decides what version should run; progressive delivery tools decide how fast traffic moves to it and roll back on bad metrics.
Common misunderstanding: "A canary needs a pipeline that shifts traffic step by step." With GitOps the commit changes the version once; a controller in the cluster runs the canary.
Definition: Argo Rollouts "is a Kubernetes controller and set of CRDs which provide advanced deployment capabilities such as blue-green, canary, canary analysis, experimentation, and progressive delivery features to Kubernetes". Flagger "is a progressive delivery tool that automates the release process for applications running on Kubernetes ... gradually shifting traffic to the new version while measuring metrics", with Canary, A/B and Blue/Green strategies through a service mesh or ingress (NGINX, Istio, Linkerd, Gateway API and others). Strategies, analysis and traffic splitting are taught in Deployment Strategies (Argo Rollouts link, Flagger link).
1 promotion commit: Rollout image 1.5.0
2 Argo CD syncs the Rollout object (health Progressing / Suspended while paused)
3 Rollouts controller: 10% -> analysis (Prometheus error rate) -> 50% -> 100%
4 bad metrics -> abort -> stable version keeps traffic; Git still says 1.5.0 -> revertReal scenarios: Flagger with Flux for a Laravel app behind NGINX; Argo Rollouts with Argo CD and Istio for the Go service.
| Tool | Pairs naturally with | Objects |
|---|---|---|
| Argo Rollouts | Argo CD (same project family; the Rollout's health shows in the app) | Rollout, AnalysisTemplate |
| Flagger | Flux (same maintainers' ecosystem) | Canary, MetricTemplate |
Fix: link the progressive controller's health into the agent so a failed analysis shows as Degraded.
GitOps for infrastructure: Crossplane preview, tf-controller Good to know
In plain words: The same loop can manage cloud resources: commit a description of a database, and a controller creates and keeps reconciling it.
Common misunderstanding: "GitOps is only for Kubernetes workloads." Any declarative API with a reconciling controller qualifies.
Definition (Crossplane preview): "Crossplane is a control plane framework for platform engineering"; "Control planes expose an API. You use the API to tell the control plane what software it should configure and how - this is your desired state." Argo CD or Flux applies Crossplane resources; Crossplane providers reconcile the cloud. tf-controller: "Tofu Controller (previously known as Weave TF-Controller) is a controller for Flux to reconcile OpenTofu and Terraform resources in the GitOps way", with models from full automation (approvePlan: auto) to "Drift Detection Model" only; with plan-and-approve "You make change to the field .spec.approvePlan, commit and push". Terraform itself: Infrastructure as Code.
# Tofu Controller (from its getting-started guide): plan and apply a Terraform module
# from a Flux source, then keep detecting drift at each interval
apiVersion: infra.contrib.fluxcd.io/v1alpha2
kind: Terraform
metadata:
name: helloworld
namespace: flux-system
spec:
interval: 1m
approvePlan: auto
path: ./
sourceRef:
kind: GitRepository
name: helloworld
namespace: flux-system1 commit: Terraform object (approvePlan: auto) for the shop's S3 bucket module
2 Tofu Controller runner pod: plan -> apply; TFSTATE stored as a Secret
3 every interval: drift detection; a console edit -> new plan appliedReal scenarios: per-environment databases created with the app; IAM policies reconciled from Git; read-only drift reports for legacy Terraform.
| Tool | Model | Drift |
|---|---|---|
| Crossplane | Kubernetes CRDs for cloud resources, compositions | Continuous (provider controllers) |
| Tofu Controller (tf-controller) | Terraform/OpenTofu runs driven by Flux | At each interval; "enabled by default" |
| Terraform in CI | Push (plan/apply jobs) | Only when the job runs |
Fix: start with read-only drift detection on existing Terraform before letting a controller apply.
Observability: sync metrics and Prometheus Important
In plain words: Scrape the agents' metrics, alert when an app stays OutOfSync or Degraded, and graph reconcile duration.
Common misunderstanding: "Slack notifications are monitoring." Notifications are events; you also need state (how many apps are OutOfSync right now?) and trends.
Definition: Argo CD's application controller exposes metrics "at the argocd-metrics:8082/metrics endpoint": argocd_app_info (labels include sync_status, health_status), argocd_app_sync_total, argocd_app_reconcile (histogram), argocd_app_k8s_request_total, argocd_app_condition, argocd_app_orphaned_resources_count; the api-server at argocd-server-metrics:8083, the repo-server at argocd-repo-server:8084 (argocd_git_request_total). Flux controllers "export Prometheus metrics at port 8080 in the standard /metrics path": gotk_reconcile_duration_seconds_*, gotk_cache_events_total, controller-runtime metrics; resource state (gotk_resource_info with ready, suspended) comes from kube-state-metrics, as in flux2-monitoring-example. Cluster-level tooling is in Kubernetes Observability.
# Argo CD: apps not Synced for 15 minutes (alert)
max by (name, project) (argocd_app_info{sync_status!="Synced"}) == 1
# Argo CD: apps Degraded
max by (name) (argocd_app_info{health_status="Degraded"}) == 1
# Flux: p95 reconcile duration per kind
histogram_quantile(0.95, sum by (kind, le) (rate(gotk_reconcile_duration_seconds_bucket[10m])))
# Flux (kube-state-metrics): objects not Ready
gotk_resource_info{ready="False"}alert pipeline
1 Prometheus scrapes argocd-metrics:8082 and Flux :8080 (+ kube-state-metrics)
2 rule "OutOfSync > 15m" fires -> Alertmanager -> on-call
3 on-call: argocd app diff / flux get kustomizations -> cause (drift, failed hook, bad render)Real scenarios: sync metrics on a dashboard per team; a spike in argocd_git_request_total after a webhook outage; a Flux Kustomization stuck in DependencyNotReady for an hour.
| Signal | Argo CD | Flux |
|---|---|---|
| Sync state | argocd_app_info{sync_status} | gotk_resource_info{ready} (KSM) |
| Health | argocd_app_info{health_status} | Ready + reason |
| Reconcile cost | argocd_app_reconcile | gotk_reconcile_duration_seconds |
| Syncs | argocd_app_sync_total | events + Alerts |
Fix: add the two OutOfSync/Degraded rules before the first production app.
Anti-patterns: kubectl apply from CI, cluster-admin CI, config in the app repo, long-lived branches Must-know
In plain words: The common ways teams say "GitOps" while still pushing, sharing god-mode credentials, or hiding environment differences.
Common misunderstanding: "We use Argo CD, so we are safe." A pipeline that also runs kubectl apply with a cluster-admin token keeps every risk of push deployment and adds an agent that will fight it.
Definition: The recurring anti-patterns:
- kubectl apply from CI anti-pattern: CI deploys directly; drift and prune are nobody's job.
- cluster-admin CI: a kubeconfig with cluster-admin in CI secrets (the "cluster-admin CI" problem); a single leak is full compromise.
- Config in app repo: manifests next to code, CI committing tags back into the same repo (Argo CD warns this "can trigger an infinite loop of build jobs and Git commit triggers").
- Long-lived branches per environment: merge drift; see Repository layouts.
- Mutable tags (
latest) in Git: the commit no longer names bytes. - Remote bases at HEAD: manifests "change their meaning from one day to the next".
- Everything in the
defaultAppProject; ApplicationSets editable by non-admins. - Self-heal fighting a controller because replicas are in Git under an HPA.
A typical "hybrid" failure
1 Argo CD syncs orders-api 1.4.2 from Git (selfHeal on)
2 legacy CI job still runs: kubectl set image ... :latest
3 Argo CD reverts to 1.4.2 within seconds; CI job reports success
4 team believes 'latest' is deployed; debugging the wrong version for hoursReal scenarios: the Before workflow in Go shows four of these in twelve lines.
| Anti-pattern | Replace with |
|---|---|
| kubectl apply from CI | CI commits or opens a PR; agent applies |
| cluster-admin CI | No cluster credentials in CI; scoped Argo CD project token if CI must trigger a sync |
| Config in app repo | Config repository (or app repo as a base referenced by the config repo) |
| Branch per environment | Directory per environment on main |
latest in Git | Release tags + digests; image automation writes them |
default project | Per-team AppProjects; admin-only ApplicationSets |
Fix: delete the deploy job, give CI a scoped token to the config repo only, and add the repository tests below.
Mechanics
One Argo CD reconcile, step by step
application-controller, per Application, every timeout.reconciliation (120s + jitter) or on refresh
1 resolve targetRevision (branch/tag/semver) to a commit SHA via repo-server (ls-remote)
2 repo-server: manifests for (repoURL, SHA, path, tool options) - cached by that key
3 normalise desired objects; read live objects from the controller's watch cache,
matched by tracking (annotation argocd.argoproj.io/tracking-id by default)
4 diff with ignoreDifferences and compare options -> per-resource Synced/OutOfSync;
tracked objects absent from desired -> marked for pruning
5 health: built-in checks + Lua customizations -> worst child wins
6 if automated and OutOfSync (and this SHA+params not already synced, or selfHeal):
sync operation: PreSync hooks -> waves (lowest first, 2s apart, wait healthy)
-> PostSync hooks; prune (reverse wave order, PruneLast at the end)
7 write status (sync, health, operationState, history entry) -> metrics, notificationsOne Flux reconcile, step by step
source-controller (GitRepository, every .spec.interval)
1 fetch ref -> if new revision: package tar.gz artifact, record revision main@sha1:<sha>, emit event
kustomize-controller (Kustomization, on interval or new artifact revision)
2 check dependsOn Ready -> else DependencyNotReady, requeue
3 download artifact, kustomize build .spec.path, SOPS decrypt, postBuild substitute
4 server-side apply dry-run against the cluster -> set of changed objects (drift included)
5 apply in stages; prune objects in the stored inventory missing from this build
6 health checks (wait / healthChecks) with .spec.timeout
7 Ready condition + inventory + lastAppliedRevision -> events -> notification-controllerKnobs
| Knob | Where | Default / example | Effect |
|---|---|---|---|
timeout.reconciliation | argocd-cm | 120s (+60s jitter) | Git poll interval; 0 disables polling (not recommended) |
--self-heal-timeout-seconds | application-controller | 5 | Delay before a self-heal sync |
ARGOCD_SYNC_WAVE_DELAY | controller env | 2 s | Pause between waves |
application.resourceTrackingMethod | argocd-cm | annotation | How Argo CD knows what it owns |
requeueAfterSeconds | ApplicationSet generator | 180 s git, 1800 s PR | Generator polling |
revisionHistoryLimit | Application | 10 | Entries for argocd app rollback |
syncWindows | AppProject | allow/deny + cron | Change windows |
.spec.interval | every Flux object | e.g. 10m | Reconcile and drift cadence |
.spec.retryInterval | Kustomization | = interval | Retry after failure |
.spec.timeout | Kustomization, HelmRelease | e.g. 5m | Build/apply/health bound |
--no-cross-namespace-refs | Flux controllers | false | Tenancy lockdown |
--no-remote-bases | kustomize-controller | false | Forbid remote Kustomize bases |
driftDetection.mode | HelmRelease | optional; warn or enabled | Helm drift detection / correction |
update.strategy | ImageUpdateAutomation | Setters | Marker-based rewrite |
Status reasons and messages you will see
| Message / reason (verbatim from the docs) | Tool | Meaning | Fix |
|---|---|---|---|
the server could not find the requested resource | Argo CD | CR whose CRD is not in the cluster or the sync | Ship the CRD in an earlier wave, or SkipDryRunOnMissingResource=true |
ComparisonError ... doesn't match $setElementOrder list | Argo CD | Duplicate keys in a merge list (e.g. env vars) | Remove duplicates in the manifest |
kustomization path not found: stat /tmp/kustomization-.../invalid: no such file or directory (ArtifactFailed) | Flux | .spec.path wrong | Fix the path (this chapter's tests catch it) |
couldn't find remote ref "refs/heads/invalid" (GitOperationFailed) | Flux | Branch does not exist | Fix ref.branch |
DependencyNotReady | Flux | A dependsOn or referenced object is not Ready | Fix the dependency first |
referenced ImageRepository does not exist | Flux | ImagePolicy points at a missing ImageRepository | Create it in the same namespace |
Failed to install after 1 attempt(s) (RetriesExceeded) | Flux helm-controller | Remediation retries used up | Read Helm events, revert or fix values |
PruneFailed, BuildFailed, HealthCheckFailed, ReconciliationFailed | Flux Kustomization | Failure class | flux events --for Kustomization/<name> |
Go
The Go side has two jobs in a GitOps setup. The service itself must make health observable (readiness and liveness endpoints, graceful shutdown), because both agents judge a rollout by it; that code is in Images & Dockerfiles and not repeated. New here are three small tools that a config repository's CI runs, written stdlib plus gopkg.in/yaml.v3: a drift model, an image-tag editor for promotion PRs, and repository policy tests. In the real config repository this module lives in tools/ (the workflows say so); in this chapter it is docs/snippets/platform/gitops-argocd-flux/go, module academy/gitops-argocd-flux, go 1.24.
Before
The push deploy most teams start with, and why it is not GitOps:
# BEFORE (anti-pattern): push-based deploy from CI. Works on day one; every line below
# is a GitOps problem. Kept to contrast with the config-repo workflows next to it.
name: deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
# 1. a long-lived kubeconfig with cluster-admin rights lives in CI secrets:
# anyone who can change this workflow (or a compromised action) owns the cluster
- run: echo "${{ secrets.PROD_KUBECONFIG }}" > kubeconfig
# 2. the cluster API must be reachable from the CI runners (a public endpoint
# or a network path from the CI provider into production)
# 3. "latest" is not a version: Git does not say what runs, rollback is guesswork
- run: kubectl --kubeconfig kubeconfig set image deployment/orders-api orders-api=ghcr.io/acme/orders-api:latest -n shop-prod
# 4. apply runs once per push; a later kubectl edit (drift) is never noticed or reverted,
# and objects deleted from the repo are never pruned
- run: kubectl --kubeconfig kubeconfig apply -k deploy/overlays/prodAfter
1. A drift model. drift.Compare matches desired and live objects by group/kind/namespace/name, compares only fields the desired state sets (so defaulted fields like clusterIP, imagePullPolicy or strategy are not drift), matches named lists (containers, ports, env) by name like a strategic merge, honours JSON-pointer ignore rules with ~1 escaping, and reports a tracked object missing from Git as needing a prune while ignoring untracked objects such as kube-root-ca.crt. It is a teaching model, not Argo CD's or Flux's algorithm (they normalise and use server-side dry-runs), but the rules it encodes are theirs.
// Package drift is a teaching model of what a GitOps agent does on every reconcile:
// compare the desired objects (rendered from Git) with the live objects (read from the
// API server) and report which are Synced, OutOfSync, Missing or would be pruned.
//
// It is NOT Argo CD's or Flux's algorithm. Argo CD normalises objects and can diff with a
// server-side dry-run; Flux's kustomize-controller asks the API server for a server-side
// apply dry-run. Both share the two rules modelled here: only fields the desired state
// sets are compared (the API server fills in defaults, so live objects always have more
// fields), and configured fields can be ignored (Argo CD ignoreDifferences, Flux
// driftDetection.ignore). Pruning is decided by ownership tracking, never by guessing.
package drift
import (
"bytes"
"errors"
"fmt"
"io"
"reflect"
"sort"
"strconv"
"strings"
"gopkg.in/yaml.v3"
)
// TrackingAnnotation is the annotation Argo CD's default "annotation" tracking method
// writes on every object it manages: "<app>:<group>/<kind>:<namespace>/<name>".
const TrackingAnnotation = "argocd.argoproj.io/tracking-id"
// Object is one Kubernetes manifest as a generic map.
type Object map[string]any
// Key identifies an object: group/kind plus namespace/name.
func (o Object) Key() string {
api, _ := o["apiVersion"].(string)
kind, _ := o["kind"].(string)
group := ""
if i := strings.Index(api, "/"); i >= 0 {
group = api[:i]
}
meta, _ := o["metadata"].(map[string]any)
ns, _ := meta["namespace"].(string)
name, _ := meta["name"].(string)
return group + "/" + kind + ":" + ns + "/" + name
}
func (o Object) annotation(key string) string {
meta, _ := o["metadata"].(map[string]any)
ann, _ := meta["annotations"].(map[string]any)
v, _ := ann[key].(string)
return v
}
// Parse splits a multi-document YAML stream into objects, skipping empty documents.
func Parse(stream []byte) ([]Object, error) {
dec := yaml.NewDecoder(bytes.NewReader(stream))
var out []Object
for {
// decode into a plain map: decoding into Object would make every nested map an
// Object too, and the type switches below expect map[string]any
var o map[string]any
err := dec.Decode(&o)
if errors.Is(err, io.EOF) {
return out, nil
}
if err != nil {
return nil, fmt.Errorf("document %d: %w", len(out)+1, err)
}
if len(o) == 0 {
continue
}
out = append(out, Object(o))
}
}
// Change is one field whose live value differs from the desired value.
type Change struct {
Path string // JSON pointer, e.g. /spec/template/spec/containers/orders-api/image
Desired any
Live any // nil when the field is missing in the live object
}
func (c Change) String() string {
if c.Live == nil {
return fmt.Sprintf("%s: missing in live (desired %v)", c.Path, c.Desired)
}
return fmt.Sprintf("%s: desired %v, live %v", c.Path, c.Desired, c.Live)
}
// Options configures a comparison.
type Options struct {
// App is the Application name used to recognise objects this app owns (tracking).
App string
// Ignore lists JSON pointers that are never reported (ignoreDifferences).
// A "~1" stands for "/" inside a key, as in RFC 6901.
Ignore []string
}
// skipped are paths no desired state should own: the API server or controllers write them.
var skipped = []string{"/status", "/metadata/managedFields", "/metadata/resourceVersion",
"/metadata/uid", "/metadata/generation", "/metadata/creationTimestamp"}
// Fields compares one desired object with its live counterpart.
func Fields(desired, live Object, opts Options) []Change {
ignore := append(append([]string{}, skipped...), opts.Ignore...)
var out []Change
walk("", map[string]any(desired), map[string]any(live), ignore, &out)
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
return out
}
func escape(k string) string { return strings.ReplaceAll(strings.ReplaceAll(k, "~", "~0"), "/", "~1") }
func ignored(path string, ignore []string) bool {
for _, p := range ignore {
if path == p || strings.HasPrefix(path, p+"/") {
return true
}
}
return false
}
func walk(path string, desired, live any, ignore []string, out *[]Change) {
if ignored(path, ignore) {
return
}
switch d := desired.(type) {
case map[string]any:
l, _ := live.(map[string]any)
for k, dv := range d {
p := path + "/" + escape(k)
lv, ok := l[k]
if !ok {
if !ignored(p, ignore) && !empty(dv) {
*out = append(*out, Change{Path: p, Desired: dv})
}
continue
}
walk(p, dv, lv, ignore, out)
}
case []any:
l, _ := live.([]any)
if named(d) {
// lists of named items (containers, ports, env) are matched by name,
// the way a strategic merge patch does, not by position
byName := map[string]any{}
for _, it := range l {
if m, ok := it.(map[string]any); ok {
if n, ok := m["name"].(string); ok {
byName[n] = m
}
}
}
for _, it := range d {
n := it.(map[string]any)["name"].(string)
p := path + "/" + escape(n)
lv, ok := byName[n]
if !ok {
*out = append(*out, Change{Path: p, Desired: it})
continue
}
walk(p, it, lv, ignore, out)
}
return
}
if !reflect.DeepEqual(normalise(d), normalise(l)) {
*out = append(*out, Change{Path: path, Desired: d, Live: live})
}
default:
if !reflect.DeepEqual(normalise(desired), normalise(live)) {
*out = append(*out, Change{Path: path, Desired: desired, Live: live})
}
}
}
// named reports whether every element is a map with a string "name" key.
func named(list []any) bool {
if len(list) == 0 {
return false
}
for _, it := range list {
m, ok := it.(map[string]any)
if !ok {
return false
}
if _, ok := m["name"].(string); !ok {
return false
}
}
return true
}
// empty treats {} and [] in the desired state as "no opinion" (Kustomize leaves
// placeholders like selector: {} that it fills in, and the API server drops empties).
func empty(v any) bool {
switch t := v.(type) {
case map[string]any:
return len(t) == 0
case []any:
return len(t) == 0
}
return false
}
// normalise makes 8080 and "8080" or 1 and 1.0 compare equal, as the API server does
// for int-or-string fields once they are stored.
func normalise(v any) any {
switch t := v.(type) {
case int:
return strconv.Itoa(t)
case float64:
return strconv.FormatFloat(t, 'f', -1, 64)
case []any:
out := make([]any, len(t))
for i, x := range t {
out[i] = normalise(x)
}
return out
case map[string]any:
out := make(map[string]any, len(t))
for k, x := range t {
out[k] = normalise(x)
}
return out
}
return v
}
// Status is the per-object result, named as Argo CD names them.
type Status string
const (
Synced Status = "Synced"
OutOfSync Status = "OutOfSync"
Missing Status = "Missing" // desired, not in the cluster: sync will create it
RequiresPrune Status = "RequiresPruning" // owned by the app, gone from Git: prune deletes it
)
// Result is one object's status with its changes.
type Result struct {
Key string
Status Status
Changes []Change
}
// Report is the outcome of comparing a whole application.
type Report struct {
Results []Result
}
// Synced reports whether the application as a whole is in sync.
func (r Report) Synced() bool {
for _, res := range r.Results {
if res.Status != Synced {
return false
}
}
return true
}
// Compare matches desired and live objects by key. A live object that is not desired is
// reported only if its tracking annotation says this app owns it; anything else in the
// namespace (objects made by controllers or by other tools) is none of the app's business.
func Compare(desired, live []Object, opts Options) Report {
liveBy := map[string]Object{}
for _, o := range live {
liveBy[o.Key()] = o
}
var rep Report
seen := map[string]bool{}
for _, d := range desired {
k := d.Key()
seen[k] = true
l, ok := liveBy[k]
if !ok {
rep.Results = append(rep.Results, Result{Key: k, Status: Missing})
continue
}
ch := Fields(d, l, opts)
st := Synced
if len(ch) > 0 {
st = OutOfSync
}
rep.Results = append(rep.Results, Result{Key: k, Status: st, Changes: ch})
}
for _, l := range live {
k := l.Key()
if seen[k] || opts.App == "" {
continue
}
if strings.HasPrefix(l.annotation(TrackingAnnotation), opts.App+":") {
rep.Results = append(rep.Results, Result{Key: k, Status: RequiresPrune})
}
}
sort.Slice(rep.Results, func(i, j int) bool { return rep.Results[i].Key < rep.Results[j].Key })
return rep
}package drift
import (
"os"
"strings"
"testing"
)
func load(t *testing.T, name string) []Object {
t.Helper()
b, err := os.ReadFile("testdata/" + name)
if err != nil {
t.Fatal(err)
}
objs, err := Parse(b)
if err != nil {
t.Fatal(err)
}
return objs
}
func byKey(r Report) map[string]Result {
m := map[string]Result{}
for _, res := range r.Results {
m[res.Key] = res
}
return m
}
// The rendered overlay against a live cluster with defaults, status, an HPA replica
// count, a manual image change and an orphaned ConfigMap.
func TestCompareRealisticLiveState(t *testing.T) {
desired := load(t, "desired-orders-api-prod.yaml")
live := load(t, "live-orders-api-prod.yaml")
rep := Compare(desired, live, Options{App: "orders-api-prod", Ignore: []string{"/spec/replicas"}})
m := byKey(rep)
if got := m["/Service:shop-prod/orders-api"].Status; got != Synced {
t.Errorf("Service: defaulted fields (clusterIP, protocol, type) must not count as drift, got %s %v",
got, m["/Service:shop-prod/orders-api"].Changes)
}
dep := m["apps/Deployment:shop-prod/orders-api"]
if dep.Status != OutOfSync || len(dep.Changes) != 1 {
t.Fatalf("Deployment: want exactly one change (the image), got %s %v", dep.Status, dep.Changes)
}
c := dep.Changes[0]
if c.Path != "/spec/template/spec/containers/orders-api/image" || !strings.Contains(c.Live.(string), "1.4.3-hotfix") {
t.Errorf("unexpected change %v", c)
}
if got := m["/ConfigMap:shop-prod/orders-api-flags"].Status; got != RequiresPrune {
t.Errorf("tracked ConfigMap missing from Git must require pruning, got %q", got)
}
if _, ok := m["/ConfigMap:shop-prod/kube-root-ca.crt"]; ok {
t.Error("an untracked object must never be reported (and never pruned)")
}
if rep.Synced() {
t.Error("report must be OutOfSync")
}
}
// Without the ignore rule, the HPA's replica count is reported as drift: the reason for
// Argo CD ignoreDifferences and Flux driftDetection.ignore on /spec/replicas.
func TestReplicasDriftWithoutIgnore(t *testing.T) {
desired := load(t, "desired-orders-api-prod.yaml")
live := load(t, "live-orders-api-prod.yaml")
desired[1]["spec"].(map[string]any)["replicas"] = 3
dep := byKey(Compare(desired, live, Options{App: "orders-api-prod"}))["apps/Deployment:shop-prod/orders-api"]
found := false
for _, c := range dep.Changes {
if c.Path == "/spec/replicas" {
found = true
}
}
if !found {
t.Errorf("want /spec/replicas drift, got %v", dep.Changes)
}
dep = byKey(Compare(desired, live, Options{App: "orders-api-prod", Ignore: []string{"/spec/replicas"}}))["apps/Deployment:shop-prod/orders-api"]
for _, c := range dep.Changes {
if c.Path == "/spec/replicas" {
t.Errorf("ignored path reported: %v", c)
}
}
}
func TestMissingObjectAndMissingField(t *testing.T) {
desired := load(t, "desired-orders-api-prod.yaml")
rep := Compare(desired, nil, Options{App: "orders-api-prod"})
for _, r := range rep.Results {
if r.Status != Missing {
t.Errorf("%s: want Missing, got %s", r.Key, r.Status)
}
}
d := Object{"spec": map[string]any{"paused": false, "selector": map[string]any{}}}
l := Object{"spec": map[string]any{}}
ch := Fields(d, l, Options{})
if len(ch) != 1 || ch[0].Path != "/spec/paused" || ch[0].Live != nil {
t.Errorf("want one missing field /spec/paused (empty selector placeholder ignored), got %v", ch)
}
}
func TestNamedListsMatchByName(t *testing.T) {
d := Object{"env": []any{
map[string]any{"name": "A", "value": "1"},
map[string]any{"name": "B", "value": "2"},
}}
l := Object{"env": []any{
map[string]any{"name": "B", "value": "2"},
map[string]any{"name": "A", "value": "1"},
}}
if ch := Fields(d, l, Options{}); len(ch) != 0 {
t.Errorf("reordered named list is not drift, got %v", ch)
}
l["env"].([]any)[0].(map[string]any)["value"] = "9"
ch := Fields(d, l, Options{})
if len(ch) != 1 || ch[0].Path != "/env/B/value" {
t.Errorf("want /env/B/value, got %v", ch)
}
}
func TestEscapedIgnorePointer(t *testing.T) {
d := Object{"metadata": map[string]any{"labels": map[string]any{"node-role.kubernetes.io/worker": "x"}}}
l := Object{"metadata": map[string]any{"labels": map[string]any{"node-role.kubernetes.io/worker": "y"}}}
if ch := Fields(d, l, Options{Ignore: []string{"/metadata/labels/node-role.kubernetes.io~1worker"}}); len(ch) != 0 {
t.Errorf("~1-escaped pointer must match, got %v", ch)
}
}// Command driftdiff compares a rendered desired state with a live state dump and prints
// an Argo CD-style sync report. Exit status: 0 Synced, 1 OutOfSync, 2 usage or input error.
//
// kubectl kustomize apps/orders-api/overlays/prod > desired.yaml
// kubectl get svc,deploy,cm -n shop-prod -o yaml > live.yaml # a List; see below
// driftdiff -desired desired.yaml -live live.yaml -app orders-api-prod -ignore /spec/replicas
//
// The live file must be a stream of objects (kubectl get -o yaml prints a v1 List; split
// it, or use one "kubectl get <kind>/<name> -o yaml" per object separated by "---").
package main
import (
"flag"
"fmt"
"os"
"strings"
"academy/gitops-argocd-flux/drift"
)
func main() {
desiredPath := flag.String("desired", "", "rendered manifests (kustomize build / helm template)")
livePath := flag.String("live", "", "live objects as a YAML stream")
app := flag.String("app", "", "application name used in the tracking annotation")
ignore := flag.String("ignore", "", "comma-separated JSON pointers to ignore")
flag.Parse()
if *desiredPath == "" || *livePath == "" {
flag.Usage()
os.Exit(2)
}
desired, err := read(*desiredPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
live, err := read(*livePath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
opts := drift.Options{App: *app}
if *ignore != "" {
opts.Ignore = strings.Split(*ignore, ",")
}
rep := drift.Compare(desired, live, opts)
for _, r := range rep.Results {
fmt.Printf("%-16s %s\n", r.Status, r.Key)
for _, c := range r.Changes {
fmt.Printf(" %s\n", c)
}
}
if rep.Synced() {
fmt.Println("application: Synced")
return
}
fmt.Println("application: OutOfSync")
os.Exit(1)
}
func read(path string) ([]drift.Object, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
objs, err := drift.Parse(b)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return objs, nil
}2. Image tag edits. imagebump.Bump changes one images: entry line by line (the promotion PR is exactly two changed lines, comments survive); ApplySetters models Flux's Setters strategy on $imagepolicy markers (full reference, :tag, :name, :digest; an unknown policy is an error; a second run is a no-op); Newest models an ImagePolicy with filterTags and a semver range (numeric ordering: 2.10.0 beats 2.8.1; pre-releases and sha- tags skipped).
// Package imagebump models the two ways a tag reaches Git in this chapter.
//
// - Bump edits one entry of a kustomization.yaml "images:" list, as a promotion pull
// request (or "kustomize edit set image", or Argo CD Image Updater's
// writeBackTarget: kustomization) does.
// - ApplySetters rewrites every value that carries a Flux setter marker such as
// # {"$imagepolicy": "flux-system:shop-app:tag"}, as Flux's image-automation-controller
// does with update.strategy: Setters.
// - BumpHelmImage does the same for a HelmRelease's values.image block, so one
// promotion moves every place that names the prod version.
// - Newest picks a tag the way a Flux ImagePolicy with filterTags + a semver range does.
//
// Both editors work line by line so comments, markers and key order survive: a YAML
// re-encode would reformat the file and make every bump PR noisy. This is a teaching
// model, not the controllers' code.
package imagebump
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
)
// Bump sets newTag (and digest, if non-empty) on the images entry whose name is image.
// It returns an error if the file has no such entry.
func Bump(src []byte, image, tag, digest string) ([]byte, error) {
lines := strings.Split(string(src), "\n")
start, indent := -1, ""
inImages := false
for i, l := range lines {
t := strings.TrimSpace(l)
if !strings.HasPrefix(l, " ") && !strings.HasPrefix(l, "-") && t != "" && !strings.HasPrefix(t, "#") {
inImages = strings.HasPrefix(t, "images:")
continue
}
if inImages && (t == "- name: "+image || t == "- name: \""+image+"\"") {
start = i
indent = l[:strings.Index(l, "-")] + " "
break
}
}
if start < 0 {
return nil, fmt.Errorf("no images entry named %q", image)
}
// the entry runs until the next "- " at the same indent or a less-indented line
end := start + 1
for end < len(lines) {
l := lines[end]
if strings.TrimSpace(l) == "" || !strings.HasPrefix(l, indent) || strings.HasPrefix(strings.TrimSpace(l), "- ") && len(l)-len(strings.TrimLeft(l, " ")) < len(indent) {
break
}
end++
}
// copy: appending to a sub-slice of lines would overwrite the line after the entry
entry := append([]string{}, lines[start+1:end]...)
entry = setKey(entry, indent, "newTag", strconv.Quote(tag))
if digest != "" {
entry = setKey(entry, indent, "digest", digest)
}
out := append(append(append([]string{}, lines[:start+1]...), entry...), lines[end:]...)
return []byte(strings.Join(out, "\n")), nil
}
// BumpHelmImage sets tag (and digest) in the YAML mapping that holds
// "repository: <repository>" (a HelmRelease's spec.values.image, for example). Sibling
// keys are matched at the repository line's indentation; comments are kept.
func BumpHelmImage(src []byte, repository, tag, digest string) ([]byte, error) {
lines := strings.Split(string(src), "\n")
at := -1
for i, l := range lines {
t := strings.TrimSpace(l)
if t == "repository: "+repository || t == "repository: \""+repository+"\"" {
at = i
break
}
}
if at < 0 {
return nil, fmt.Errorf("no \"repository: %s\" line", repository)
}
indent := lines[at][:len(lines[at])-len(strings.TrimLeft(lines[at], " "))]
start, end := at, at+1
for start > 0 && strings.HasPrefix(lines[start-1], indent) && !strings.HasPrefix(lines[start-1], indent+" ") && strings.TrimSpace(lines[start-1]) != "" && !strings.HasSuffix(strings.TrimSpace(lines[start-1]), ":") {
start--
}
for end < len(lines) && strings.HasPrefix(lines[end], indent) && strings.TrimSpace(lines[end]) != "" {
end++
}
block := append([]string{}, lines[start:end]...)
block = setKey(block, indent, "tag", strconv.Quote(tag))
if digest != "" {
block = setKey(block, indent, "digest", digest)
}
out := append(append(append([]string{}, lines[:start]...), block...), lines[end:]...)
return []byte(strings.Join(out, "\n")), nil
}
// setKey replaces "key: value" inside an entry (keeping a trailing comment) or appends it.
func setKey(entry []string, indent, key, value string) []string {
for i, l := range entry {
if strings.HasPrefix(strings.TrimSpace(l), key+":") {
comment := ""
if j := strings.Index(l, " #"); j >= 0 {
comment = l[j:]
}
entry[i] = indent + key + ": " + value + comment
return entry
}
}
return append(entry, indent+key+": "+value)
}
// Policy is the latest image an ImagePolicy selected, e.g. ghcr.io/acme/shop-app:2.8.2.
type Policy struct {
Repository string
Tag string
Digest string // optional
}
// Change is one rewritten line.
type Change struct {
Line int
Marker string
Old, New string
}
var markerRE = regexp.MustCompile(`#\s*(\{"\$imagepolicy":\s*"[^"]+"\})\s*$`)
// ApplySetters rewrites every value that carries an $imagepolicy marker. policies is keyed
// by "<namespace>:<name>". Marker suffixes: none = full reference, ":tag", ":name",
// ":digest". A marker naming an unknown policy is an error: the automation would silently
// never update that field.
func ApplySetters(src []byte, policies map[string]Policy) ([]byte, []Change, error) {
lines := strings.Split(string(src), "\n")
var changes []Change
for i, l := range lines {
m := markerRE.FindStringSubmatchIndex(l)
if m == nil {
continue
}
var marker struct {
Ref string `json:"$imagepolicy"`
}
if err := json.Unmarshal([]byte(l[m[2]:m[3]]), &marker); err != nil {
return nil, nil, fmt.Errorf("line %d: %w", i+1, err)
}
parts := strings.Split(marker.Ref, ":")
if len(parts) < 2 || len(parts) > 3 {
return nil, nil, fmt.Errorf("line %d: marker %q is not <ns>:<name>[:field]", i+1, marker.Ref)
}
p, ok := policies[parts[0]+":"+parts[1]]
if !ok {
return nil, nil, fmt.Errorf("line %d: no ImagePolicy %s:%s", i+1, parts[0], parts[1])
}
field := ""
if len(parts) == 3 {
field = parts[2]
}
var val string
switch field {
case "":
val = p.Repository + ":" + p.Tag
case "tag":
val = p.Tag
case "name":
val = p.Repository
case "digest":
val = p.Digest
default:
return nil, nil, fmt.Errorf("line %d: unknown marker field %q", i+1, field)
}
head := strings.TrimRight(l[:m[0]], " ")
colon := strings.Index(head, ": ")
if colon < 0 {
return nil, nil, fmt.Errorf("line %d: marker not on a key: value line", i+1)
}
old := strings.TrimSpace(head[colon+2:])
quoted := strings.HasPrefix(old, "\"")
bare := strings.Trim(old, "\"")
if bare == val {
continue
}
nv := val
if quoted {
nv = strconv.Quote(val)
}
lines[i] = head[:colon+2] + nv + " " + l[m[0]:]
changes = append(changes, Change{Line: i + 1, Marker: marker.Ref, Old: bare, New: val})
}
return []byte(strings.Join(lines, "\n")), changes, nil
}
type semver struct{ major, minor, patch int }
func parse(s string) (semver, bool) {
s = strings.TrimPrefix(s, "v")
f := strings.Split(s, ".")
if len(f) != 3 {
return semver{}, false
}
var v [3]int
for i, x := range f {
n, err := strconv.Atoi(x)
if err != nil || n < 0 {
return semver{}, false // pre-releases (1.2.3-rc.1) and junk are skipped
}
v[i] = n
}
return semver{v[0], v[1], v[2]}, true
}
func (a semver) less(b semver) bool {
if a.major != b.major {
return a.major < b.major
}
if a.minor != b.minor {
return a.minor < b.minor
}
return a.patch < b.patch
}
// Newest returns the highest release tag that matches pattern (nil = all tags) and lies in
// [min, maxExclusive). ok is false when nothing qualifies: the policy keeps its old value.
func Newest(tags []string, pattern *regexp.Regexp, min, maxExclusive string) (tag string, ok bool) {
lo, ok1 := parse(min)
hi, ok2 := parse(maxExclusive)
if !ok1 || !ok2 {
return "", false
}
var best semver
for _, t := range tags {
if pattern != nil && !pattern.MatchString(t) {
continue
}
v, ok := parse(t)
if !ok || v.less(lo) || !v.less(hi) {
continue
}
if tag == "" || best.less(v) {
best, tag = v, t
}
}
return tag, tag != ""
}package imagebump
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"academy/gitops-argocd-flux/repocheck"
)
// repoFile resolves a path inside the config repository in either layout (this
// knowledge base, or the real repository with the module in tools/).
func repoFile(t *testing.T, rel string) string {
t.Helper()
root, err := repocheck.FindRoot(".")
if err != nil {
t.Fatal(err)
}
return filepath.Join(root, rel)
}
func TestBumpPromotionKeepsComments(t *testing.T) {
src, err := os.ReadFile(repoFile(t, "apps/orders-api/overlays/prod/kustomization.yaml"))
if err != nil {
t.Fatal(err)
}
out, err := Bump(src, "ghcr.io/acme/orders-api", "1.5.0", "sha256:1111111111111111111111111111111111111111111111111111111111111111")
if err != nil {
t.Fatal(err)
}
s := string(out)
for _, want := range []string{
` newTag: "1.5.0"`,
` digest: sha256:1111111111111111111111111111111111111111111111111111111111111111`,
"# placeholder digest; the promotion PR writes the digest CI printed for 1.4.2",
"namespace: shop-prod",
} {
if !strings.Contains(s, want) {
t.Errorf("missing %q in:\n%s", want, s)
}
}
// exactly two lines differ: a reviewable one-entry PR
a, b := strings.Split(string(src), "\n"), strings.Split(s, "\n")
if len(a) != len(b) {
t.Fatalf("line count changed %d -> %d", len(a), len(b))
}
diff := 0
for i := range a {
if a[i] != b[i] {
diff++
}
}
if diff != 2 {
t.Errorf("want 2 changed lines, got %d", diff)
}
}
func TestBumpUnknownImage(t *testing.T) {
src, _ := os.ReadFile(repoFile(t, "apps/orders-api/overlays/prod/kustomization.yaml"))
if _, err := Bump(src, "ghcr.io/acme/nope", "1.0.0", ""); err == nil {
t.Error("want error for an image that is not in the overlay")
}
}
func TestBumpAddsMissingKey(t *testing.T) {
src := []byte("images:\n - name: ghcr.io/acme/x\n newName: ghcr.io/acme/y\nreplicas: []\n")
out, err := Bump(src, "ghcr.io/acme/x", "2.0.0", "")
if err != nil {
t.Fatal(err)
}
want := "images:\n - name: ghcr.io/acme/x\n newName: ghcr.io/acme/y\n newTag: \"2.0.0\"\nreplicas: []\n"
if string(out) != want {
t.Errorf("got\n%s", out)
}
}
// One ImagePolicy owns both Laravel images, so both lines move in the same commit.
func TestApplySettersOnLaravelOverlay(t *testing.T) {
src, err := os.ReadFile(repoFile(t, "apps/shop-laravel/overlays/staging/kustomization.yaml"))
if err != nil {
t.Fatal(err)
}
pol := map[string]Policy{"flux-system:shop-laravel": {Repository: "ghcr.io/acme/shop-app", Tag: "2.9.0"}}
out, ch, err := ApplySetters(src, pol)
if err != nil {
t.Fatal(err)
}
if len(ch) != 2 {
t.Fatalf("want both images bumped together, got %+v", ch)
}
for _, c := range ch {
if c.Old != "2.8.1" || c.New != "2.9.0" || c.Marker != "flux-system:shop-laravel:tag" {
t.Errorf("unexpected change %+v", c)
}
}
if got := strings.Count(string(out), `newTag: "2.9.0" # {"$imagepolicy": "flux-system:shop-laravel:tag"}`); got != 2 {
t.Errorf("want 2 rewritten lines with marker kept, got %d:\n%s", got, out)
}
if _, ch2, _ := ApplySetters(out, pol); len(ch2) != 0 {
t.Errorf("second run changed %v", ch2)
}
}
func TestBumpHelmImageOnHelmRelease(t *testing.T) {
src, err := os.ReadFile(repoFile(t, "clusters/prod/helmrelease-orders-api.yaml"))
if err != nil {
t.Fatal(err)
}
d := "sha256:2222222222222222222222222222222222222222222222222222222222222222"
out, err := BumpHelmImage(src, "ghcr.io/acme/orders-api", "1.5.0", d)
if err != nil {
t.Fatal(err)
}
s := string(out)
for _, want := range []string{` tag: "1.5.0"`, " digest: " + d, "# the promote-to-prod workflow bumps tag and digest here", "driftDetection:"} {
if !strings.Contains(s, want) {
t.Errorf("missing %q in:\n%s", want, s)
}
}
if strings.Count(s, "\n") != strings.Count(string(src), "\n") {
t.Error("line count changed")
}
if _, err := BumpHelmImage(src, "ghcr.io/acme/nope", "1", ""); err == nil {
t.Error("want error for an unknown repository")
}
}
func TestApplySettersFields(t *testing.T) {
src := []byte(strings.Join([]string{
`image: ghcr.io/acme/shop-app:2.0.0 # {"$imagepolicy": "flux-system:shop-app"}`,
`repository: old/name # {"$imagepolicy": "flux-system:shop-app:name"}`,
`tag: 2.0.0 # {"$imagepolicy": "flux-system:shop-app:tag"}`,
}, "\n"))
out, ch, err := ApplySetters(src, map[string]Policy{"flux-system:shop-app": {Repository: "ghcr.io/acme/shop-app", Tag: "2.1.0"}})
if err != nil || len(ch) != 3 {
t.Fatalf("err=%v changes=%v", err, ch)
}
want := strings.Join([]string{
`image: ghcr.io/acme/shop-app:2.1.0 # {"$imagepolicy": "flux-system:shop-app"}`,
`repository: ghcr.io/acme/shop-app # {"$imagepolicy": "flux-system:shop-app:name"}`,
`tag: 2.1.0 # {"$imagepolicy": "flux-system:shop-app:tag"}`,
}, "\n")
if string(out) != want {
t.Errorf("got\n%s", out)
}
if _, _, err := ApplySetters(src, map[string]Policy{}); err == nil {
t.Error("a marker naming an unknown policy must be an error")
}
}
func TestNewest(t *testing.T) {
tags := []string{"2.7.0", "2.8.1", "2.10.0", "3.0.0", "2.11.0-rc.1", "sha-4f2a9c1", "latest", "1.9.9"}
release := regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
if got, ok := Newest(tags, release, "2.0.0", "3.0.0"); !ok || got != "2.10.0" {
t.Errorf(">=2.0.0 <3.0.0: got %q (numeric, not alphabetical: 2.10.0 > 2.8.1)", got)
}
if got, ok := Newest(tags, release, "2.8.0", "2.9.0"); !ok || got != "2.8.1" {
t.Errorf("2.8.x: got %q", got)
}
if _, ok := Newest(tags, release, "4.0.0", "5.0.0"); ok {
t.Error("nothing in range must keep the old value")
}
}// Command imagebump sets the tag (and digest) of one image, in place, keeping comments:
// in a kustomization.yaml images: entry (-format kustomize, the default) or in a
// HelmRelease values block that holds "repository: <image>" (-format helm). The
// promote-to-prod workflow runs it on every file that names the prod version.
//
// imagebump -file apps/orders-api/overlays/prod/kustomization.yaml \
// -image ghcr.io/acme/orders-api -tag 1.5.0 -digest sha256:...
// imagebump -format helm -file clusters/prod/helmrelease-orders-api.yaml \
// -image ghcr.io/acme/orders-api -tag 1.5.0 -digest sha256:...
package main
import (
"flag"
"fmt"
"os"
"regexp"
"academy/gitops-argocd-flux/imagebump"
)
var digestRE = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
func main() {
file := flag.String("file", "", "kustomization.yaml to edit")
image := flag.String("image", "", "images[].name to change")
tag := flag.String("tag", "", "new tag")
digest := flag.String("digest", "", "new digest (sha256:<64 hex>), optional")
format := flag.String("format", "kustomize", "kustomize (images: entry) or helm (values image block)")
flag.Parse()
if *file == "" || *image == "" || *tag == "" {
flag.Usage()
os.Exit(2)
}
if *digest != "" && !digestRE.MatchString(*digest) {
fmt.Fprintf(os.Stderr, "digest %q is not sha256:<64 hex>\n", *digest)
os.Exit(2)
}
src, err := os.ReadFile(*file)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var out []byte
switch *format {
case "kustomize":
out, err = imagebump.Bump(src, *image, *tag, *digest)
case "helm":
out, err = imagebump.BumpHelmImage(src, *image, *tag, *digest)
default:
err = fmt.Errorf("unknown -format %q", *format)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := os.WriteFile(*file, out, 0o644); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("%s: %s -> %s %s\n", *file, *image, *tag, *digest)
}3. Repository policy tests. Every YAML document parses; no Application or ApplicationSet uses the default project or a templated project; only the platform project may target argocd; hook annotations name real phases; every Flux Kustomization reading this repo has prune and an existing path; every dependsOn resolves; every marker names an existing ImagePolicy; a prod marker is only written by an automation that pushes to a separate branch; prod tags without a marker carry a digest.
// Package repocheck loads a GitOps config repository and checks the rules a reviewer
// would otherwise have to remember. Its tests run in the config repo's CI on every pull
// request, before any agent sees the change.
package repocheck
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"gopkg.in/yaml.v3"
)
// Doc is one YAML document with the file it came from.
type Doc struct {
File string
Obj map[string]any
}
// Kind returns apiVersion group + kind, e.g. "kustomize.toolkit.fluxcd.io/Kustomization".
func (d Doc) Kind() string {
api, _ := d.Obj["apiVersion"].(string)
kind, _ := d.Obj["kind"].(string)
if i := strings.Index(api, "/"); i >= 0 {
api = api[:i]
}
return api + "/" + kind
}
// Name returns metadata.namespace/metadata.name.
func (d Doc) Name() string {
return Str(d.Obj, "metadata", "namespace") + "/" + Str(d.Obj, "metadata", "name")
}
// Str walks nested maps and returns the string at the end ("" if absent).
func Str(m map[string]any, path ...string) string {
v := Get(m, path...)
s, _ := v.(string)
return s
}
// Get walks nested maps.
func Get(m map[string]any, path ...string) any {
var cur any = m
for _, p := range path {
mm, ok := cur.(map[string]any)
if !ok {
return nil
}
cur = mm[p]
}
return cur
}
// Load parses every .yaml/.yml file under root (all documents). A parse error is fatal:
// an agent that cannot parse the repository deploys nothing.
func Load(root string) ([]Doc, error) {
var docs []Doc
err := filepath.WalkDir(root, func(path string, e fs.DirEntry, err error) error {
if err != nil {
return err
}
if e.IsDir() || !(strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml")) {
return nil
}
b, err := os.ReadFile(path)
if err != nil {
return err
}
rel, _ := filepath.Rel(root, path)
dec := yaml.NewDecoder(bytes.NewReader(b))
for i := 1; ; i++ {
var o map[string]any
err := dec.Decode(&o)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("%s document %d: %w", rel, i, err)
}
if len(o) > 0 {
docs = append(docs, Doc{File: rel, Obj: o})
}
}
return nil
})
return docs, err
}
var markerRE = regexp.MustCompile(`\{"\$imagepolicy":\s*"([^":]+):([^":]+)(:[a-z]+)?"\}`)
// Marker is one Flux setter marker found in a file.
type Marker struct {
File, Policy string // Policy is "<namespace>/<name>"
}
// Markers finds every $imagepolicy marker under root.
func Markers(root string) ([]Marker, error) {
var out []Marker
err := filepath.WalkDir(root, func(path string, e fs.DirEntry, err error) error {
if err != nil || e.IsDir() || !strings.HasSuffix(path, ".yaml") {
return err
}
b, err := os.ReadFile(path)
if err != nil {
return err
}
rel, _ := filepath.Rel(root, path)
for _, m := range markerRE.FindAllSubmatch(b, -1) {
out = append(out, Marker{File: rel, Policy: string(m[1]) + "/" + string(m[2])})
}
return nil
})
return out, err
}package repocheck
import (
"os"
"path/filepath"
"strings"
"testing"
)
// root is the config repository: REPO_ROOT, or found from this package's directory in
// either layout (tools/repocheck in the real repo, go/repocheck in this knowledge base).
var root = func() string {
r, err := FindRoot(".")
if err != nil {
panic(err)
}
return r
}()
func docs(t *testing.T) []Doc {
t.Helper()
d, err := Load(root)
if err != nil {
t.Fatal(err)
}
if len(d) < 30 {
t.Fatalf("only %d documents loaded", len(d))
}
return d
}
func TestEveryYAMLFileParses(t *testing.T) {
docs(t)
wf := FindWorkflows(root)
if wf == "" {
t.Fatal("no workflow directory found")
}
if _, err := Load(wf); err != nil {
t.Fatal(err)
}
}
// Argo CD: nothing deploys through the wide-open "default" project, and only the
// admin-level "platform" project may target the argocd namespace.
func TestArgoProjects(t *testing.T) {
projects := map[string]bool{}
for _, d := range docs(t) {
if d.Kind() == "argoproj.io/AppProject" {
name := Str(d.Obj, "metadata", "name")
projects[name] = true
dests, _ := Get(d.Obj, "spec", "destinations").([]any)
for _, x := range dests {
ns, _ := x.(map[string]any)["namespace"].(string)
if ns == "argocd" && name != "platform" {
t.Errorf("%s: project %s may deploy into argocd (admin-level)", d.File, name)
}
}
}
}
for _, d := range docs(t) {
var project string
switch d.Kind() {
case "argoproj.io/Application":
project = Str(d.Obj, "spec", "project")
case "argoproj.io/ApplicationSet":
project = Str(d.Obj, "spec", "template", "spec", "project")
default:
continue
}
if project == "" || project == "default" || strings.Contains(project, "{{") {
t.Errorf("%s %s: project %q (empty, default or templated)", d.File, d.Name(), project)
} else if !projects[project] {
t.Errorf("%s %s: project %q is not defined in the repo", d.File, d.Name(), project)
}
}
}
// Argo CD hook annotations must use a phase Argo CD knows; a typo silently makes the
// Job a normal resource that runs in parallel with the rollout.
func TestArgoHookPhases(t *testing.T) {
valid := map[string]bool{"PreSync": true, "Sync": true, "Skip": true, "PostSync": true,
"SyncFail": true, "PreDelete": true, "PostDelete": true}
for _, d := range docs(t) {
h := Str(d.Obj, "metadata", "annotations", "argocd.argoproj.io/hook")
for _, p := range strings.Split(h, ",") {
if h != "" && !valid[strings.TrimSpace(p)] {
t.Errorf("%s: unknown hook phase %q", d.File, p)
}
}
}
}
// Flux: every Kustomization that reads this repository points at a directory that exists
// and states prune explicitly (it is a required field).
func TestFluxKustomizationPaths(t *testing.T) {
ours := map[string]bool{"flux-system": true, "shop-config": true}
n := 0
for _, d := range docs(t) {
if d.Kind() != "kustomize.toolkit.fluxcd.io/Kustomization" {
continue
}
if _, ok := Get(d.Obj, "spec", "prune").(bool); !ok {
t.Errorf("%s %s: spec.prune must be set", d.File, d.Name())
}
if !ours[Str(d.Obj, "spec", "sourceRef", "name")] {
continue // a tenant's own repository
}
p := Str(d.Obj, "spec", "path")
if fi, err := os.Stat(filepath.Join(root, p)); err != nil || !fi.IsDir() {
t.Errorf("%s %s: path %q does not exist", d.File, d.Name(), p)
}
n++
}
if n < 5 {
t.Errorf("only %d Kustomizations checked", n)
}
}
// Flux: every dependsOn names a Kustomization defined in the same cluster directory.
func TestFluxDependsOn(t *testing.T) {
byDir := map[string]map[string]bool{}
all := docs(t)
for _, d := range all {
if d.Kind() == "kustomize.toolkit.fluxcd.io/Kustomization" {
dir := filepath.Dir(d.File)
if byDir[dir] == nil {
byDir[dir] = map[string]bool{}
}
byDir[dir][Str(d.Obj, "metadata", "name")] = true
}
}
for _, d := range all {
deps, _ := Get(d.Obj, "spec", "dependsOn").([]any)
for _, x := range deps {
name, _ := x.(map[string]any)["name"].(string)
if !byDir[filepath.Dir(d.File)][name] {
t.Errorf("%s %s: dependsOn %q not defined in %s", d.File, d.Name(), name, filepath.Dir(d.File))
}
}
}
}
// Image automation: every setter marker names an existing ImagePolicy, and a marker in a
// prod overlay is only updated by an automation that pushes to a separate branch (a PR).
// Prod images without a marker must pin a digest.
func TestImageAutomationRules(t *testing.T) {
policies := map[string]bool{}
type iua struct{ path, checkout, push string }
var autos []iua
for _, d := range docs(t) {
switch d.Kind() {
case "image.toolkit.fluxcd.io/ImagePolicy":
policies[d.Name()] = true
case "image.toolkit.fluxcd.io/ImageUpdateAutomation":
autos = append(autos, iua{
path: filepath.Clean(Str(d.Obj, "spec", "update", "path")),
checkout: Str(d.Obj, "spec", "git", "checkout", "ref", "branch"),
push: Str(d.Obj, "spec", "git", "push", "branch"),
})
}
}
ms, err := Markers(root)
if err != nil {
t.Fatal(err)
}
if len(ms) == 0 {
t.Fatal("no markers found")
}
for _, m := range ms {
if !policies[m.Policy] {
t.Errorf("%s: marker names unknown ImagePolicy %s", m.File, m.Policy)
}
if !strings.Contains(m.File, "/prod/") {
continue
}
covered := false
for _, a := range autos {
if strings.HasPrefix(m.File, a.path+"/") {
covered = true
if a.push == "" || a.push == a.checkout {
t.Errorf("%s: prod marker updated by an automation that pushes straight to %s", m.File, a.checkout)
}
}
}
if !covered {
t.Errorf("%s: prod marker not covered by any ImageUpdateAutomation", m.File)
}
}
// prod overlays: an image entry needs a digest or a marker
files, _ := filepath.Glob(filepath.Join(root, "apps/*/overlays/prod/kustomization.yaml"))
for _, f := range files {
b, _ := os.ReadFile(f)
for _, l := range strings.Split(string(b), "\n") {
if strings.HasPrefix(strings.TrimSpace(l), "newTag:") && !strings.Contains(l, "$imagepolicy") &&
!strings.Contains(string(b), "digest: sha256:") {
t.Errorf("%s: prod tag without digest or automation marker", f)
}
}
}
}
// FindRoot must work in both layouts and honour REPO_ROOT.
func TestFindRootLayouts(t *testing.T) {
t.Setenv("REPO_ROOT", "") // the layout cases below must not inherit the caller's REPO_ROOT
real := t.TempDir() // real config repo: apps/ at the top, module in tools/
for _, d := range []string{"apps", "tools/repocheck", ".github/workflows"} {
if err := os.MkdirAll(filepath.Join(real, d), 0o755); err != nil {
t.Fatal(err)
}
}
got, err := FindRoot(filepath.Join(real, "tools", "repocheck"))
if err != nil || got != filepath.Clean(real) {
t.Errorf("real layout: got %q, %v", got, err)
}
if wf := FindWorkflows(got); wf != filepath.Join(real, ".github", "workflows") {
t.Errorf("real layout workflows: %q", wf)
}
kb := t.TempDir() // this knowledge base: config-repo/ and ci/ next to go/
for _, d := range []string{"config-repo/apps", "go/repocheck", "ci"} {
if err := os.MkdirAll(filepath.Join(kb, d), 0o755); err != nil {
t.Fatal(err)
}
}
got, err = FindRoot(filepath.Join(kb, "go", "repocheck"))
if err != nil || got != filepath.Join(kb, "config-repo") {
t.Errorf("kb layout: got %q, %v", got, err)
}
if wf := FindWorkflows(got); filepath.Clean(wf) != filepath.Join(kb, "ci") {
t.Errorf("kb layout workflows: %q", wf)
}
t.Setenv("REPO_ROOT", real)
if got, err := FindRoot("/nonexistent"); err != nil || got != real {
t.Errorf("REPO_ROOT: got %q, %v", got, err)
}
t.Setenv("REPO_ROOT", filepath.Join(kb, "go"))
if _, err := FindRoot("."); err == nil {
t.Error("REPO_ROOT without apps/ must be an error")
}
}module academy/gitops-argocd-flux
go 1.24
require gopkg.in/yaml.v3 v3.0.1The config repository's CI, which runs these tests and publishes the signed OCI artifact:
# Config repository CI. Pull requests: render every overlay and run the repository
# policy tests; nothing touches a cluster. Pushes to main: publish the repository as a
# signed OCI artifact and move the "prod" tag that prod clusters pull. The approval gate
# is the reviewed PR that changed overlays/prod; the tag only says "this commit is
# published". During a change freeze, stop moving the tag (skip this job).
name: config-repo
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: tools/go.mod
# every overlay must build; a broken overlay would make the agent report a
# build error instead of deploying
- name: Render all overlays
run: |
set -euo pipefail
for k in $(find apps infrastructure -name kustomization.yaml); do
dir=$(dirname "$k")
echo "::group::$dir"
kubectl kustomize "$dir" > /dev/null
echo "::endgroup::"
done
# repository policy: YAML parses, every Flux path exists, no Application uses the
# default project, prod overlays pin a digest, markers name a real ImagePolicy
- name: Repository policy tests
working-directory: tools
run: go test ./...
publish:
if: github.event_name == 'push'
needs: validate
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # push to ghcr.io
id-token: write # keyless cosign signing with the workflow's OIDC identity
env:
OCI_REPO: oci://ghcr.io/acme/shop-config
steps:
- uses: actions/checkout@v7
- uses: fluxcd/flux2/action@main
with:
version: '2.10.1'
- uses: sigstore/cosign-installer@v4.1.4
- uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Push, sign and tag for prod clusters
run: |
set -euo pipefail
digest_url=$(flux push artifact "$OCI_REPO:$(git rev-parse --short HEAD)" \
--path="." \
--source="$(git config --get remote.origin.url)" \
--revision="main@sha1:$(git rev-parse HEAD)" \
--output=json | jq -r '.repository + "@" + .digest')
cosign sign --yes "$digest_url"
flux tag artifact "$OCI_REPO:$(git rev-parse --short HEAD)" --tag prodAnd the Go service as Argo CD sees it in Git (the "Go service Application" is orders-api-prod above; these are the overlays it renders):
# orders-api base: environment-neutral. Overlays reference this directory; it never knows them.
# Packaging details (labels, generators, components) are taught in the Helm/Kustomize chapter.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
labels:
- pairs:
app.kubernetes.io/name: orders-api
app.kubernetes.io/part-of: shop
includeSelectors: true
images:
- name: orders-api
newName: ghcr.io/acme/orders-api
newTag: "1.4.2"apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
spec:
# no "replicas:" here: an HPA owns the count in prod, and a GitOps agent would
# otherwise fight it on every reconcile (the "leave room for imperativeness" rule)
selector:
matchLabels: {}
template:
metadata:
labels: {}
spec:
automountServiceAccountToken: false
terminationGracePeriodSeconds: 30
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
containers:
- name: orders-api
image: orders-api
ports:
- name: http
containerPort: 8080
# Argo CD marks the Deployment Healthy and Flux's health check passes only when
# the rollout completes, which needs these probes to go green
readinessProbe:
httpGet:
path: /readyz
port: http
livenessProbe:
httpGet:
path: /healthz
port: http
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi# staging: tracks the newest 1.x build. Argo CD Image Updater commits the tag here
# (writeBackTarget: kustomization), exactly as "kustomize edit set image" would.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-staging
resources:
- ../../base
labels:
- pairs:
app.kubernetes.io/environment: staging
images:
- name: ghcr.io/acme/orders-api
newTag: "1.5.0"
replicas:
- name: orders-api
count: 1# prod: changed only by a reviewed pull request (the promotion PR copies the tag that
# passed staging). The digest pins the exact bytes; the tag stays for humans.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-prod
resources:
- ../../base
labels:
- pairs:
app.kubernetes.io/environment: prod
images:
- name: ghcr.io/acme/orders-api
newTag: "1.4.2"
# placeholder digest; the promotion PR writes the digest CI printed for 1.4.2
digest: sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3The Go angle
- Both agents are Go programs built on the same libraries. Argo CD and Flux use client-go and controller-runtime-style reconcilers; Flux publishes its controllers' APIs as Go modules (
github.com/fluxcd/*), and Argo CD's Application types are in its repository. This chapter deliberately does not import them: the tools stay ongo 1.24with one dependency, and the YAML shape is checked by the tests instead. - Readiness decides health. Argo CD marks a Deployment Healthy when updated replicas equal desired; that only happens if
/readyzturns green. Flip readiness off beforesrv.Shutdownso old pods leave endpoints before they stop (shown in the Images chapter's service). - Version visibility. Stamp the version with
-ldflags "-X main.version=..."and expose it (/version); after a sync,curl /versionis the cheapest proof that the cluster runs what Git says. - Writing your own reconciler. The loop in Mechanics is the operator pattern; building one in Go with controller-runtime is Extending Kubernetes.
- Testing manifests in Go.
yaml.v3decodes multi-document streams withDecoder.Decodeuntilio.EOF; decode intomap[string]any(a named map type would make every nested map that type too, which the drift model's first test run caught). - Image automation for Go services works best with immutable semver tags from
git tagand a separatesha-tag for traceability;filterTagskeeps the policy on releases.
Laravel
Before
A Laravel deploy script run by CI against production, typical of push setups:
# Before: SSH/kubectl deploy from CI; ordering lives in a script, not in the desired state
kubectl -n shop-prod set image deploy/shop-web php-fpm=ghcr.io/acme/shop-app:latest
kubectl -n shop-prod exec deploy/shop-web -c php-fpm -- php artisan migrate --force # runs in a serving pod
kubectl -n shop-prod rollout status deploy/shop-web || echo "ignore, it usually works"
# no smoke test, no record in Git of what runs, worker Deployment forgottenAfter
The Laravel app as two Deployments (web with php-fpm + Nginx, worker running queue:work) and release Jobs, delivered by the "Laravel Kustomization" in Flux (or by the ApplicationSet in Argo CD). Migrations run once per release as a PreSync hook (Argo CD) or a forced Job the Kustomization waits for (Flux), with --isolated so two concurrent runs cannot both migrate. The smoke test is a PostSync hook under Argo CD (after everything is Healthy); under Flux, which has no phases, the command itself establishes the order by polling the web Service's /version until it reports the Job's own image version, and only then checks the database, the new schema and the cache.
# shop-laravel base: one app image (php-fpm) runs as web and worker; Nginx fronts php-fpm
# inside the web pod. Image build details: the Images & Dockerfiles chapter.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- web.yaml
- worker.yaml
- service.yaml
labels:
- pairs:
app.kubernetes.io/part-of: shop-laravel
images:
# containers name the real repository without a tag; each overlay sets the tag
- name: ghcr.io/acme/shop-app
newTag: "2.7.0"
- name: ghcr.io/acme/shop-web
newTag: "2.7.0"apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-web
labels:
app.kubernetes.io/name: shop-web
spec:
selector:
matchLabels:
app.kubernetes.io/name: shop-web
template:
metadata:
labels:
app.kubernetes.io/name: shop-web
spec:
containers:
- name: php-fpm
image: ghcr.io/acme/shop-app
envFrom:
# created outside Git (External Secrets Operator or a SOPS-decrypted Secret)
- secretRef:
name: shop-laravel-env
- name: nginx
image: ghcr.io/acme/shop-web
ports:
- name: http
containerPort: 8080
# Laravel's built-in health route; the rollout (and so the GitOps health
# status) only completes when /up answers 200
readinessProbe:
httpGet:
path: /up
port: httpapiVersion: apps/v1
kind: Deployment
metadata:
name: shop-worker
labels:
app.kubernetes.io/name: shop-worker
spec:
selector:
matchLabels:
app.kubernetes.io/name: shop-worker
template:
metadata:
labels:
app.kubernetes.io/name: shop-worker
spec:
terminationGracePeriodSeconds: 120
containers:
- name: worker
image: ghcr.io/acme/shop-app
command: ["php", "artisan", "queue:work", "--max-time=3600"]
envFrom:
- secretRef:
name: shop-laravel-env# Release jobs that run once per sync: migrations before, a smoke test after.
# Argo CD reads the hook annotations; Flux ignores them and applies the Jobs as normal
# objects (force: enabled recreates a Job whose immutable template changed).
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- migrate-job.yaml
- smoke-job.yaml# prod: the same markers, but the prod ImageUpdateAutomation pushes to a separate branch,
# so every bump arrives as a pull request that a human approves (promotion by PR).
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-prod
resources:
- ../../base
- ../../release-jobs
labels:
- pairs:
app.kubernetes.io/environment: prod
images:
- name: ghcr.io/acme/shop-app
newTag: "2.7.0" # {"$imagepolicy": "flux-system:shop-laravel:tag"}
- name: ghcr.io/acme/shop-web
newTag: "2.7.0" # {"$imagepolicy": "flux-system:shop-laravel:tag"}
replicas:
- name: shop-web
count: 3
- name: shop-worker
count: 2The smoke test as an Artisan command (Laravel 13 APIs as documented: DB::select, Schema::hasColumn, Cache::put / Cache::pull, the HTTP client's Http::timeout(...)->get(...)), and the /version route it polls (config('app.version') reads an APP_VERSION baked into the image):
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* Post-deploy smoke test.
*
* Argo CD runs it as a PostSync hook, i.e. after every resource is Healthy. Flux has no
* hook phases: the Job starts in the same reconcile as the new Deployments, so the first
* check waits (bounded) until the web Service answers /version with THIS image's
* version, which proves new pods serve traffic. Only then are the dependency checks run.
* A non-zero exit fails the Job: Argo CD marks the sync failed (on-sync-failed), Flux keeps
* the Kustomization not Ready (wait: true) and the error Alert fires.
*/
class SmokeTest extends Command
{
protected $signature = 'app:smoke-test
{--url=http://shop-web : Base URL of the web Service inside the namespace}
{--attempts=30 : Polls of /version before giving up}
{--interval=5 : Seconds between polls}';
protected $description = 'Verify the deployed release against its real dependencies';
public function handle(): int
{
$expected = (string) config('app.version', 'unknown');
if (! $this->waitForRelease($expected)) {
$this->error("web: release {$expected} never served /version");
return self::FAILURE;
}
$checks = [
'database' => fn () => (int) DB::select('select 1 as ok')[0]->ok === 1,
// the newest migration of this release; fails if the migrate Job did not run
'schema' => fn () => Schema::hasColumn('orders', 'fulfilment_status'),
'cache' => function () {
$key = 'smoke:'.bin2hex(random_bytes(4));
Cache::put($key, 'ok', 30);
return Cache::pull($key) === 'ok';
},
];
$failed = 0;
foreach ($checks as $name => $check) {
try {
$ok = (bool) $check();
} catch (Throwable $e) {
$ok = false;
$this->error("{$name}: ".$e->getMessage());
}
$ok ? $this->info("{$name}: ok") : $this->error("{$name}: FAILED");
$failed += $ok ? 0 : 1;
}
$this->line(sprintf('release %s: %d/%d checks passed', $expected, count($checks) - $failed, count($checks)));
return $failed === 0 ? self::SUCCESS : self::FAILURE;
}
/**
* Poll GET {url}/version until it reports the expected version. Old pods (previous
* release) and pods that are not ready yet both count as "not yet".
*/
private function waitForRelease(string $expected): bool
{
$url = rtrim((string) $this->option('url'), '/').'/version';
for ($i = 1; $i <= (int) $this->option('attempts'); $i++) {
try {
$response = Http::timeout(3)->get($url);
$seen = $response->successful() ? (string) $response->json('version') : 'HTTP '.$response->status();
} catch (Throwable $e) {
$seen = $e->getMessage();
}
if ($seen === $expected) {
$this->info("web: {$url} serves {$expected} (attempt {$i})");
return true;
}
$this->line("web: attempt {$i}: {$seen}");
sleep((int) $this->option('interval'));
}
return false;
}
}<?php
// routes/web.php (excerpt): the version endpoint the smoke test polls. APP_VERSION is
// baked into the image at build time, so web pods and the smoke Job report the same
// value only when the new release is the one serving traffic.
use Illuminate\Support\Facades\Route;
Route::get('/version', function () {
return ['version' => config('app.version')];
});The Laravel angle
- Migrations are a release step, not a container start step. Laravel prompts before destructive migrations in production; "To force the commands to run without a prompt, use the --force flag". With several clusters or a retried sync,
--isolatedmakes Laravel "acquire an atomic lock using your application's cache driver before attempting to run your migrations" (the cache must be shared, e.g. Redis). - Migrations must be backwards compatible. Under Argo CD the PreSync Job runs before the new pods; under Flux the migrate Job, the smoke Job and the Deployments are applied in the same reconcile (the smoke Job's
backoffLimit: 4absorbs that race; a stricter setup splits the Jobs into a separate Kustomization and orders it withdependsOn). In both, old pods serve during the rollout, so expand first (add nullable columns), contract in a later release. That is also what makes rollback by revert safe. - Health route. Laravel's built-in
/up"will return a 200 HTTP response if the application has booted without exceptions"; use it as the readiness probe so the agent's health status means something. - Configuration.
.envdoes not belong in Git; the overlays reference theshop-laravel-envSecret, delivered by SOPS (Flux) or ESO.php artisan optimizebelongs in the container entrypoint (see Images & Dockerfiles), where the real environment exists. - Workers and drift.
queue:work --max-time=3600exits hourly and is restarted by Kubernetes; that is not drift (the pod spec does not change). Akubectl rollout restartadds arestartedAtannotation that Flux removes again unless run with--field-manager=flux-client-side-apply. - Image automation of the Laravel tag (the "image automation Laravel tag" flow in Flux image automation). CI tags
shop-appandshop-webwith the same release version and pushesshop-webfirst. One ImagePolicy (shop-laravel, on theshop-apprepository) owns both overlay lines through the same marker, so both tags change in one commit; two independent policies would not guarantee that.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| CI holds cluster-admin | Pull agent | Argo CD/Flux in cluster; CI writes Git only | No cluster credentials outside | Agent to operate |
| Nobody knows what runs | Git as the record | Tags + digests in overlays; agent status | git log answers | Discipline: no side doors |
| Manual hotfixes linger | Self-heal / drift correction | selfHeal: true; Flux interval | Snowflakes impossible | Incidents need suspend |
| Deleted manifests keep running | Prune | prune: true, Prune=false exceptions | Clean namespaces | A bad commit can delete; allowEmpty guard |
| Migrations race the rollout | Hooks / ordered Jobs | PreSync Job, --isolated, expand/contract | One run per release | Hook failures block deploys |
| Every env needs N YAML files | ApplicationSet / cluster dirs | git × cluster matrix | New app = new directory | Admin-only templates |
| Staging lags releases | Image automation | Flux ImageUpdateAutomation / Image Updater | No manual bumps | Bot with Git write access |
| Prod must be approved | PR-based promotion | Automation to a branch, or CI PR | Review = change record | Slower |
| Rollback | git revert | Revert promotion commit | Git and cluster agree | Data migrations are not reverted |
| Slow delivery | Webhooks | Argo CD /api/webhook, Flux Receiver | Seconds | Webhook endpoint exposure |
| Secrets in Git | SOPS / Sealed Secrets / ESO | See Secrets | No plaintext | Key management |
| HPA flapping | Ignore or omit replicas | ignoreDifferences, driftDetection.ignore | Stable | Must remember per field |
Migrating from push to pull without an outage
Install the agent with automated sync off, create Applications/Kustomizations pointing at today's manifests, and read the diff: every OutOfSync object is a manual change nobody committed. Commit the ones you want, then enable automated sync, then prune, then self-heal, one environment at a time; delete the CI deploy job last.
Previews per pull request
Use the pull request generator (Argo CD) with a fixed project (shop-previews) whose destinations allow only orders-api-pr-* namespaces, and a preview overlay that sets no namespace: the Application's kustomize.namespace puts every object into orders-api-pr-<number>. Rendering the staging overlay instead would fail, because destination.namespace "will only be set for namespace-scoped resources that have not set a value for .metadata.namespace" and that overlay sets shop-staging; CI pushes pr-<short sha> images; the Application is deleted when the PR closes. Flux has no PR generator; teams template a Kustomization per PR from CI or use a separate tool.
An app stuck OutOfSync after every sync
Run argocd app diff (expected, not run) and look at the field: defaulted by the API server (manifest has an invalid or extra field), owned by a controller (add ignoreDifferences or remove from Git), randomised by a chart (randAlphaNum), or a resource Argo CD wants to prune with prune off.
Choosing
Argo CD or Flux
| Situation | Choose | Reason |
|---|---|---|
| Many teams want a UI, SSO and per-app RBAC | Argo CD | Built-in UI, Dex/OIDC, Casbin RBAC, AppProjects |
| One central instance managing many clusters | Argo CD | Hub model with registered clusters |
| Each cluster self-contained, no UI needed | Flux | Agent per cluster, Kubernetes RBAC only |
| Heavy use of third-party Helm charts with hooks/tests | Flux (or Argo CD knowing hooks are mapped) | Real Helm releases and remediation |
| Image automation without extra projects | Flux | Controllers in the same toolkit |
| PR preview environments | Argo CD | Pull request generator |
| Strict multi-tenancy on shared clusters | Flux | Impersonation + lockdown flags |
| Promotion pipelines across stages | Either + Kargo | Neither has promotion built in |
Repository layout
| Team shape | Layout |
|---|---|
| One team, a few services | Monorepo config repo, overlays per env |
| Platform team + app teams | Repo per team, platform repo onboards tenant repos |
| Regulated prod | Repo per environment for prod |
| Many clusters per env | clusters/<name>/ dirs + shared apps/ overlays |
How tags reach Git
| Environment | Mechanism |
|---|---|
| dev / preview | CI sets the tag (Application kustomize.images or PR generator) |
| staging | Image automation commits to main |
| prod | Promotion PR (bot, Flux branch push, Image Updater branch, Kargo) with digest |
In architecture: from a single process to a distributed system
GitOps changes who may change a running system and how that change is recorded. The architectural questions are how many repositories, how many agents, and where each cluster pulls from.
Monolith: one app, one cluster, one Application
The Laravel monolith in one cluster: one config repo with apps/shop-laravel/overlays/{staging,prod}, one Argo CD instance (or Flux bootstrapped per cluster), automated sync with prune and self-heal, migrations as a PreSync Job, and a promotion PR to prod. Even here the essentials hold: no cluster credentials in CI, readiness on /up, and rollback by revert.
Modular monolith: one repo, several deployables
The same codebase produces web, worker and a Go sidecar service. Each gets a directory under apps/, an ApplicationSet (or Kustomizations) generates them, and dependsOn or sync waves order shared pieces (namespaces, CRDs, the database operator) before the apps. One version number across the deployables keeps promotion a single PR.
Microservices: many teams, many apps
Twenty services with their own repositories and teams. The platform team owns the config repository's clusters/, infrastructure/ and argocd/ (or tenants/); each team owns apps/<service>/ via CODEOWNERS, or its own repo onboarded as a Flux tenant. A release of orders-api v1.5.0:
1 orders-api repo: tag v1.5.0 -> CI builds, tests, scans, signs ghcr.io/acme/orders-api:1.5.0@D
2 Image Updater commits 1.5.0 to apps/orders-api/overlays/staging (git write-back)
3 Argo CD staging: sync, PostSync smoke, Healthy; notification to #orders
4 promote-to-prod workflow opens PR (tag + digest D); orders team approves; merge
5 ApplicationSet-generated orders-api-prod syncs in the sync window; Rollouts canary 10% -> 100%
6 metrics: argocd_app_info{name="orders-api-prod", health_status="Healthy"}Contracts between services (APIs, events) still need versioning; GitOps only guarantees that what runs is what was reviewed.
Distributed data: many clusters, regions and registries
At fleet scale the source of truth itself becomes a dependency: if GitHub is down, nothing changes, and if every cluster polls every two minutes, the Git host rate-limits you. Patterns: webhooks plus longer polls; OCI artifacts replicated to regional registries (each cluster pulls the signed config from a nearby registry, verified by digest and cosign identity); cluster labels driving ApplicationSet cluster generators so a new region gets the right apps; controller sharding for an Argo CD hub with many clusters; or an agent per cluster (Flux, or Argo CD per cluster) so a hub outage does not stop reconciliation. Data stays outside Git: databases have their own replication; GitOps manages the operator objects, not the rows.
Scaling path: 1x, 10x, 100x
| Scale | Repos and layout | Agents | Delivery |
|---|---|---|---|
| 1x (one team, one cluster) | Monorepo config repo, overlays per env | One Argo CD or Flux | Image automation to staging, PR to prod |
| 10x (several teams, 2-5 clusters) | Repo per team or CODEOWNERS; ApplicationSets; tenants | Argo CD HA with projects, or Flux per cluster with tenancy | Webhooks, sync windows, notifications, OutOfSync alerts |
| 100x (fleet, regions) | clusters/<name> generated by cluster labels; OCI artifacts | Sharded Argo CD or Flux per cluster; Kargo for promotion | Signed artifacts, regional registries, progressive delivery everywhere |
Lab
Label: no Kubernetes cluster may be started in this build environment (AUTHORING cost rule). Steps 1-4 ran on the host (macOS, Go 1.27.4, kubectl client v1.36.1 with Kustomize v5.8.1) and show real output, saved in pipeline/sources/gitops-argocd-flux/lab-host-output.txt. Steps 5-8 are expected, not run: their output is written as shape or placeholders, never invented values.
1. Render every overlay like the agents do (ran on the host)
cd docs/snippets/platform/gitops-argocd-flux
scripts/render-overlays.sh ~/.docker/bin/kubectl
# ok apps/orders-api/overlays/preview 1 Deployment, 1 Service
# images: ghcr.io/acme/orders-api:1.4.2
# ok apps/orders-api/overlays/prod 1 Deployment, 1 Service
# images: ghcr.io/acme/orders-api:1.4.2@sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3
# ok apps/orders-api/overlays/staging 1 Deployment, 1 Service
# images: ghcr.io/acme/orders-api:1.5.0
# ok apps/shop-laravel/overlays/prod 2 Deployment, 2 Job, 1 Service
# images: ghcr.io/acme/shop-app:2.7.0 ghcr.io/acme/shop-web:2.7.0
# ok apps/shop-laravel/overlays/staging 2 Deployment, 2 Job, 1 Service
# images: ghcr.io/acme/shop-app:2.8.1 ghcr.io/acme/shop-web:2.8.1
# ok infrastructure/namespaces 2 Namespace
# images: noneNote the prod image: with both newTag and digest, Kustomize writes name:tag@digest; the digest decides what is pulled.
What a preview Application renders for PR 42: the same as a wrapper kustomization with namespace: and the PR image, which is what kustomize.namespace and kustomize.images in the preview ApplicationSet amount to (ran on the host):
cat sim/kustomization.yaml
# namespace: orders-api-pr-42
# resources: [../config-repo/apps/orders-api/overlays/preview]
# images: [{name: ghcr.io/acme/orders-api, newTag: pr-4f2a9c1e}]
kubectl kustomize sim | grep 'namespace:\|image:'
# namespace: orders-api-pr-42
# namespace: orders-api-pr-42
# - image: ghcr.io/acme/orders-api:pr-4f2a9c1e#!/usr/bin/env bash
# Render every overlay of the config repository exactly as Argo CD's repo-server and
# Flux's kustomize-controller would (kustomize build), without a cluster.
# Usage: scripts/render-overlays.sh [kubectl] (default: kubectl on PATH)
set -euo pipefail
kubectl=${1:-kubectl}
cd "$(dirname "$0")/../config-repo"
status=0
for dir in apps/*/overlays/* infrastructure/*; do
if out=$("$kubectl" kustomize "$dir" 2>&1); then
kinds=$(printf '%s\n' "$out" | awk '/^kind:/{print $2}' | sort | uniq -c | awk '{printf "%s %s, ", $1, $2}')
images=$(printf '%s\n' "$out" | awk '/image:/{print $NF}' | sort -u | tr '\n' ' ')
printf 'ok %-40s %s\n images: %s\n' "$dir" "${kinds%, }" "${images:-none}"
else
printf 'FAIL %s\n%s\n' "$dir" "$out"; status=1
fi
done
exit $status2. Repository policy tests (ran on the host)
cd go && gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ? academy/gitops-argocd-flux/cmd/driftdiff [no test files]
# ? academy/gitops-argocd-flux/cmd/imagebump [no test files]
# ok academy/gitops-argocd-flux/drift 1.292s
# ok academy/gitops-argocd-flux/imagebump 1.287s
# ok academy/gitops-argocd-flux/repocheck 1.419sBreak a rule to see the gate work: change push.branch: image-updates/shop-prod to main in clusters/staging/image-automation.yaml and rerun (done on the host, then restored):
--- FAIL: TestImageAutomationRules
repocheck_test.go:170: apps/shop-laravel/overlays/prod/kustomization.yaml: prod marker updated by an automation that pushes straight to main3. Drift: what an agent would report (ran on the host)
desired is the real kubectl kustomize output of the prod overlay; live is a hand-written sample of what a cluster returns after a week (defaults, status, an HPA count of 7, one kubectl set image hotfix, a ConfigMap the app once owned).
# still in the go/ directory from step 2
go run ./cmd/driftdiff -desired drift/testdata/desired-orders-api-prod.yaml \
-live drift/testdata/live-orders-api-prod.yaml -app orders-api-prod -ignore /spec/replicas; echo "exit=$?"
# RequiresPruning /ConfigMap:shop-prod/orders-api-flags
# Synced /Service:shop-prod/orders-api
# OutOfSync apps/Deployment:shop-prod/orders-api
# /spec/template/spec/containers/orders-api/image: desired ghcr.io/acme/orders-api:1.4.2@sha256:0b7e...e2f3, live ghcr.io/acme/orders-api:1.4.3-hotfix
# application: OutOfSync
# exit status 1
# exit=1The digest is shortened here; the saved output has it in full. The Service is Synced although the live object has a dozen extra fields; the 7 replicas are not reported even without -ignore, because the base omits replicas (run it without the flag: same output). kube-root-ca.crt is not reported because nothing tracks it. RequiresPruning is this model's label; Argo CD shows the app OutOfSync with the resource marked for pruning.
4. A promotion edit (ran on the host, on a scratch copy)
# still in go/; work on a temporary copy, never on the overlay itself
T=$(mktemp); cp ../config-repo/apps/orders-api/overlays/prod/kustomization.yaml "$T"
go run ./cmd/imagebump -file "$T" -image ghcr.io/acme/orders-api \
-tag 1.5.0 -digest sha256:1111111111111111111111111111111111111111111111111111111111111111
# $T: ghcr.io/acme/orders-api -> 1.5.0 sha256:1111111111111111111111111111111111111111111111111111111111111111
diff ../config-repo/apps/orders-api/overlays/prod/kustomization.yaml "$T"; rm "$T"
# 13c13
# < newTag: "1.4.2"
# ---
# > newTag: "1.5.0"
# 15c15
# < digest: sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3
# ---
# > digest: sha256:11111111111111111111111111111111111111111111111111111111111111115. Argo CD: install, register, sync (expected, not run)
kubectl create namespace argocd
kubectl apply -n argocd --server-side --force-conflicts -f https://raw.githubusercontent.com/argoproj/argo-cd/v3.6.3/manifests/install.yaml
# the root app belongs to the "platform" project, which lives inside the directory the
# root app syncs: create that one project by hand first, then the root app adopts it
kubectl apply -f config-repo/argocd/project-platform.yaml
kubectl apply -f config-repo/argocd/root-app.yaml # app of apps: projects, ApplicationSets, cluster Secret
argocd app list
# NAME CLUSTER NAMESPACE PROJECT STATUS HEALTH ...
# argocd/root in-cluster argocd platform Synced Healthy
# argocd/orders-api-staging in-cluster shop-staging shop Synced Healthy
# ... (one row per generated Application)
argocd app diff orders-api-prod # exit code non-zero when there is a diff
argocd app history orders-api-prod6. Drift and self-heal on a live app (expected, not run)
kubectl -n shop-staging set image deploy/orders-api orders-api=ghcr.io/acme/orders-api:9.9.9
argocd app get orders-api-staging # Sync Status: OutOfSync, then Synced again a few seconds later (selfHeal)
kubectl -n shop-staging get deploy orders-api -o jsonpath='{.spec.template.spec.containers[0].image}'
# ghcr.io/acme/orders-api:1.5.07. Flux: bootstrap with image automation, watch a tag land (expected, not run)
flux bootstrap github --components-extra=image-reflector-controller,image-automation-controller \
--owner=acme --repository=shop-config --branch=main --path=clusters/staging --read-write-key
flux get kustomizations
# NAME REVISION SUSPENDED READY MESSAGE
# flux-system main@sha1:<sha> False True Applied revision: main@sha1:<sha>
# infrastructure main@sha1:<sha> False True Applied revision: main@sha1:<sha>
# shop-laravel-staging main@sha1:<sha> False True Applied revision: main@sha1:<sha>
kubectl -n flux-system get imagepolicy shop-app # status shows the latest image ghcr.io/acme/shop-app:<newest 2.x tag>
git pull && git log -1 --stat # commit by fluxcdbot touching overlays/staging/kustomization.yaml
flux events --for Kustomization/shop-laravel-staging8. Rollback by revert vs the button (expected, not run)
git revert --no-edit <promotion-sha> && git push # PR in real life
argocd app wait orders-api-prod --sync --health
argocd app rollback orders-api-prod # refused while automated sync is enabledCommon misconceptions
| Belief | Reality |
|---|---|
| GitOps = YAML in Git | Also pulled automatically and continuously reconciled |
| Git is required | Any state store with immutable versions; OCI artifacts work ("Gitless") |
| Argo CD reverts manual changes by default | Only with selfHeal: true; automated sync is opt-in too |
| Automated sync deletes removed resources | Only with prune: true |
| Synced means the release works | Health is separate: Synced + Degraded is common |
argocd app rollback is the GitOps rollback | Refused with auto-sync on; leaves Git disagreeing. Revert the commit |
| Branch per environment is clean | Hidden differences and merge drift; use directories on main |
| Image automation updates the cluster | It writes back to Git; the agent deploys the commit |
| Argo CD Image Updater commits to Git by default | Default write-back method is argocd (in-cluster, "pseudo-persistent") |
| Flux installs image automation | Needs --components-extra |
| A private repo makes plaintext Secrets OK | Flux docs: unsafe "regardless of the visibility" |
| ApplicationSets are safe for every team | Admin-only: they can create apps in any project and read Argo CD secrets |
| Webhooks are required | Polling works; webhooks only reduce latency |
| Argo CD and Flux treat Helm alike | Argo CD renders and applies; Flux runs real Helm releases |
Cheat sheet
| Topic | Remember |
|---|---|
| Principles | Declarative, versioned and immutable, pulled automatically, continuously reconciled |
| Push vs pull | CI writes Git; agent in cluster applies; no cluster creds in CI |
| Layout | Config repo, main only, overlay per env, CODEOWNERS on prod |
| Argo CD parts | api-server (UI/CLI/RBAC/webhooks), repo-server (render), application-controller (diff/sync), Redis (cache) |
| Sync policy | automated + prune + selfHeal; retry; ServerSideApply=true |
| Ordering | Argo CD: PreSync -> waves -> PostSync; Flux: dependsOn, wait |
| Status | Sync (Synced/OutOfSync) and health (Healthy/Progressing/Degraded) are different |
| Ignore | ignoreDifferences / driftDetection.ignore; better: omit controller-owned fields |
| ApplicationSet | git × cluster matrix; PR generator for previews; admin-only |
| Flux objects | GitRepository/OCIRepository -> Kustomization/HelmRelease; Provider/Alert/Receiver |
| Image automation | ImageRepository -> ImagePolicy -> ImageUpdateAutomation -> marker -> commit |
| Promotion | Tag + digest PR into overlays/prod; Kargo for multi-stage |
| Rollback | git revert; argocd app rollback needs auto-sync off |
| Secrets | SOPS, Sealed Secrets or ESO; never plaintext |
| Metrics | argocd_app_info{sync_status,health_status}; gotk_reconcile_duration_seconds; alert on OutOfSync > 15m |
| Anti-patterns | kubectl apply from CI, cluster-admin CI, latest, default project, branch per env |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What are the four OpenGitOps principles, and which two does a CI job running kubectl apply -k on every push violate? Must-know
Answer
Answer: Declarative; versioned and immutable; pulled automatically; continuously reconciled. The CI job can satisfy the first two (manifests in Git), but it pushes rather than an agent pulling, and it applies once per run instead of continuously observing and correcting drift, so manual changes and deleted manifests go unnoticed. See Principles.
2 — Your Argo CD Application has automated: {}. Someone deletes a Deployment manifest from Git and someone else scales another Deployment by hand. What happens to each, and what do you change? Must-know
Answer
Answer: Neither is corrected: automated sync does not prune by default, and live changes do not trigger a sync without self-heal, so the app shows OutOfSync. Set prune: true (protect critical objects with Prune=false or Prune=confirm) and selfHeal: true. See Sync policy.
3 — Why is one branch per environment considered an anti-pattern, and what replaces it? Must-know
Answer
Answer: Environment differences hide in merge history, merges drag unrelated changes into prod, cherry-picks drift, and you cannot diff environments in one command. Use one branch (main) with a directory per environment (Kustomize overlays or Helm values per env); promotion becomes a small reviewed diff in overlays/prod. See Repository layouts.
4 — An app is Synced but Degraded. What does each word tell you, and where do you look? Must-know
Answer
Answer: Synced: the live objects match what Git renders. Degraded: the workload is not working, e.g. pods in CrashLoopBackOff or a failed rollout. Look at the Deployment's rollout, pod events and logs, not at Git; fix by reverting or by a new commit. See Health.
5 — How do you run Laravel migrations exactly once per release under Argo CD, and why must they be backwards compatible anyway? Must-know
Answer
Answer: A Job annotated argocd.argoproj.io/hook: PreSync with BeforeHookCreation, running php artisan migrate --force --isolated; a failure stops the sync before new pods are applied. Old pods keep serving during the rolling update (and after a rollback by revert), so the schema must work for both versions: expand first, contract later. See Waves and hooks.
6 — Why does a rollback in GitOps mean git revert, and when does argocd app rollback fail? Must-know
Answer
Answer: A revert creates a new commit that restores the previous desired state, so Git and the cluster agree and the audit trail stays complete. argocd app rollback re-syncs an older history entry and "cannot be performed against an application with automated sync enabled"; after it, Git still names the bad version. See Rollback.
7 — Walk through Flux image automation of the Laravel tag from registry push to running pods. Important
Answer
Answer: image-reflector-controller scans the ImageRepository; the ImagePolicy filters tags (filterTags) and picks the newest in the semver range; image-automation-controller checks out the branch, rewrites fields carrying {"$imagepolicy": "flux-system:shop-laravel:tag"} markers (one policy for both Laravel images) under update.path, commits and pushes; source-controller fetches the new revision and the Kustomization applies it. For prod, push.branch differs from the checkout branch so the change arrives as a PR. See Image automation.
8 — Why are ApplicationSets and app-of-apps repositories admin-only? Important
Answer
Answer: They can create Applications in any AppProject, including projects that may deploy into the Argo CD namespace (admin-level), they can create or delete many Applications quickly, and the git generator can send Secrets from the Argo CD namespace to URLs as auth headers. Keep templates' project fixed and restrict who can push to their source paths. See ApplicationSet.
9 — An HPA scales a Deployment and Argo CD shows it OutOfSync every few minutes. Give two fixes and say which you prefer. Important
Answer
Answer: Remove replicas from the manifest in Git (preferred: nothing to ignore, the HPA owns the field), or add ignoreDifferences with jsonPointers: [/spec/replicas] for Deployments (and RespectIgnoreDifferences=true if sync must not reset it). In Flux HelmReleases use driftDetection.ignore. See Diffing.
10 — How do Argo CD and Flux differ in the way they deploy a Helm chart? Important
Answer
Answer: Argo CD's repo-server runs helm template and Argo CD applies the output, so no Helm release exists (helm list is empty) and Helm hooks are mapped to Argo CD hooks. Flux's helm-controller performs real Helm installs and upgrades, keeps release history, runs Helm tests, remediates failures (retry, rollback by default, uninstall) and can correct drift with driftDetection.mode: enabled. See HelmRelease.
11 — During an incident you must change a live Deployment by hand. How do you do it safely under GitOps? Important
Answer
Answer: Suspend reconciliation for that app first (Flux flux suspend kustomization <name> or the kustomize.toolkit.fluxcd.io/reconcile: disabled annotation on one object; Argo CD: disable automated sync for that Application, and if an ApplicationSet generated it, make sure the ApplicationSet has ignoreApplicationDifferences on /spec/syncPolicy, because otherwise editing the generated Application's sync policy "will, however, have no effect"), make the change, commit the real fix through a PR, then resume. Otherwise self-heal or the next interval reverts your change mid-incident. See Drift and self-heal.
12 — What does Kargo add on top of Argo CD, in its own words? Good to know
Answer
Answer: Promotion, not deployment: "Promotions are different from deployments"; deploying "is left to a GitOps agent like Argo CD". Kargo's Warehouses watch repositories and package new revisions into Freight ("a 'meta-artifact'"), which moves through linked Stages by Promotions. See Promotion.
13 — Why would you deliver config to production clusters as a signed OCI artifact instead of a Git clone? Good to know
Answer
Answer: The Git host stops being a production dependency, regional registries can serve the artifact close to each cluster, the artifact is content-addressed, and an OCIRepository can verify a cosign signature (for example keyless, tied to the config repo's CI workflow identity) before anything is applied. Git stays the human interface. See Flux sources.
Glossary
| Term | Meaning |
|---|---|
| GitOps | Operating a system from a versioned desired state that agents pull and continuously reconcile |
| OpenGitOps principles | The CNCF GitOps Working Group's four principles (v1.0.0, 2021) |
| Declarative | Describes the end state, not the steps |
| Versioned and immutable | Every desired-state version kept, never rewritten |
| Pulled automatically | Agents fetch desired state themselves |
| Continuously reconciled | Agents keep comparing and correcting, not once |
| Desired state | Configuration sufficient to recreate the system (not its data) |
| State store | Immutable, access-controlled store of desired state (Git, OCI registry) |
| Reconciliation loop | Fetch, render, diff, apply, check health, repeat |
| Drift | Live state moving away from desired state |
| Self-heal | Agent re-applying desired state after drift (Argo CD selfHeal) |
| Drift detection | The diff step; Flux HelmRelease driftDetection |
| Push vs pull deployment | CI applies to the cluster vs an in-cluster agent pulls |
| Config repository | Repo holding deployable configuration, separate from code |
| App repository | Repo holding application source code |
| Monorepo | All environments' config in one repo and branch |
| Per-environment directories | overlays/staging, overlays/prod on one branch |
| Branches per environment anti-pattern | Using a Git branch per env; merge drift |
| Kustomize overlays | Base plus per-env patches (see the Helm/Kustomize chapter) |
| Helm values per env | values-<env>.yaml files per environment |
| Argo CD | CNCF GitOps CD tool with UI, projects and RBAC |
| api-server | argocd-server: gRPC/REST API, UI, RBAC, SSO, webhooks |
| repo-server | Argo CD component that clones and renders manifests |
| application-controller | Argo CD controller that diffs and syncs Applications |
| Redis | Argo CD's disposable cache |
| Application CRD | Argo CD object: source, destination, project, sync policy |
| AppProject | Argo CD guard rails: repos, destinations, kinds, roles, windows |
| Sync policy | spec.syncPolicy: automated, prune, selfHeal, retry, options |
| Automated sync | Sync without a click when OutOfSync |
| Prune | Deleting resources removed from the source |
| Sync options | Per-app or per-resource flags (ServerSideApply, PruneLast ...) |
| Sync waves | sync-wave annotation ordering resources |
| Sync hooks | Resources run at PreSync, Sync, PostSync, SyncFail, PreDelete, PostDelete |
| Health status | Healthy, Progressing, Degraded, Suspended, Missing, Unknown |
| OutOfSync | Live state differs from the rendered target |
| ignoreDifferences | Argo CD rules that exclude fields from the diff |
| ApplicationSet | Template + generators producing Applications |
| Git generator | Parameters from repo directories or files |
| Cluster generator | Parameters from Argo CD cluster Secrets |
| Matrix generator | Product of two generators' parameters |
| Pull request generator | Parameters from open PRs (previews) |
| App of apps | An Application whose manifests are Applications |
| Argo CD RBAC | Casbin policies in argocd-rbac-cm |
| SSO | Login through Dex or an OIDC provider |
| Argo CD Notifications | Triggers, templates and services in argocd-notifications-cm |
| Argo CD Image Updater | Controller updating image tags of Argo CD apps (ImageUpdater CR) |
| Flux | CNCF GitOps toolkit of controllers |
| source-controller | Fetches Git/OCI/Helm/Bucket sources into artifacts |
| kustomize-controller | Builds and applies Kustomizations, prunes, decrypts SOPS |
| helm-controller | Runs Helm releases for HelmRelease objects |
| notification-controller | Webhooks in (Receiver), events out (Alert/Provider) |
| image-reflector-controller | Scans registries for ImageRepository/ImagePolicy |
| image-automation-controller | Writes selected tags back to Git |
| GitRepository | Flux source for a Git repo |
| OCIRepository | Flux source for an OCI artifact |
| OCI artifacts | Config or charts stored in a container registry |
| Kustomization (Flux) | CRD that applies a path of a source; not the kustomization.yaml file |
| HelmRelease | Flux CRD for a Helm release |
| dependsOn | Flux ordering between Kustomizations/HelmReleases |
| Health checks | Flux healthChecks / wait on applied objects |
| Receiver | Flux webhook endpoint triggering reconciles |
| Alert, Provider | Flux event routing and destination |
| ImageRepository | Flux object listing an image's tags |
| ImagePolicy | Flux rule choosing the latest allowed tag |
| ImageUpdateAutomation | Flux object committing new tags to Git |
| Write back to Git | Image automation committing changes instead of patching the cluster |
$imagepolicy marker | YAML comment telling Flux which field to update |
| flux bootstrap | Installing Flux and committing its manifests so it manages itself |
| Multi-tenancy | Tenants reconciled under their own ServiceAccounts |
| Secrets in GitOps | Encrypted (SOPS, Sealed Secrets) or referenced (ESO) secrets |
| Environment promotion | Moving a tested version to the next environment's desired state |
| Image tag bump PR | Pull request changing one image tag (and digest) |
| Kargo | Promotion platform: Warehouse, Freight, Stage, Promotion |
| Rollback by revert | git revert of the change; the agent syncs it |
| argocd app rollback | Re-sync an older Application history entry |
| Argo Rollouts | Progressive delivery controller (canary, blue-green) |
| Flagger | Progressive delivery operator for meshes/ingress |
| Crossplane | Control-plane framework managing cloud resources via CRDs |
| tf-controller (Tofu Controller) | Flux controller reconciling Terraform/OpenTofu |
| Sync metrics | argocd_app_info, argocd_app_sync_total, gotk_* in Prometheus |
| kubectl apply from CI | Push deploy anti-pattern |
| cluster-admin CI | CI holding cluster-wide admin credentials |
| Long-lived branches | Branches kept per environment or feature for weeks |
| Sync window | AppProject schedule allowing or denying syncs |
| Tracking annotation | argocd.argoproj.io/tracking-id, how Argo CD knows ownership |
References
- OpenGitOps: principles https://opengitops.dev/ — Principles v1.0.0 text https://raw.githubusercontent.com/open-gitops/documents/main/PRINCIPLES.md — Glossary https://raw.githubusercontent.com/open-gitops/documents/main/GLOSSARY.md — releases https://github.com/open-gitops/documents/releases
- Argo CD: overview https://argo-cd.readthedocs.io/en/stable/ — getting started https://argo-cd.readthedocs.io/en/stable/getting_started/ — core concepts https://argo-cd.readthedocs.io/en/stable/core_concepts/ — architecture https://argo-cd.readthedocs.io/en/stable/operator-manual/architecture/ — declarative setup https://argo-cd.readthedocs.io/en/stable/operator-manual/declarative-setup/ — application spec https://argo-cd.readthedocs.io/en/stable/user-guide/application-specification/ — high availability https://argo-cd.readthedocs.io/en/stable/operator-manual/high_availability/
- Argo CD sync: automated sync https://argo-cd.readthedocs.io/en/stable/user-guide/auto_sync/ — sync options https://argo-cd.readthedocs.io/en/stable/user-guide/sync-options/ — waves and hooks https://argo-cd.readthedocs.io/en/stable/user-guide/sync-waves/ — resource hooks https://argo-cd.readthedocs.io/en/stable/user-guide/resource_hooks/ — sync windows https://argo-cd.readthedocs.io/en/stable/user-guide/sync_windows/ — health https://argo-cd.readthedocs.io/en/stable/operator-manual/health/ — diffing https://argo-cd.readthedocs.io/en/stable/user-guide/diffing/ — resource tracking https://argo-cd.readthedocs.io/en/stable/user-guide/resource_tracking/ — tracking strategies https://argo-cd.readthedocs.io/en/stable/user-guide/tracking_strategies/ — OCI sources https://argo-cd.readthedocs.io/en/stable/user-guide/oci/ — webhooks https://argo-cd.readthedocs.io/en/stable/operator-manual/webhook/ — FAQ https://argo-cd.readthedocs.io/en/stable/faq/ — best practices https://argo-cd.readthedocs.io/en/stable/user-guide/best_practices/
- Argo CD ApplicationSet: intro https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/ — generators https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators/ — git https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators-Git/ — cluster https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators-Cluster/ — matrix https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators-Matrix/ — pull request https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators-Pull-Request/ — security https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Security/ — cluster bootstrapping (app of apps) https://argo-cd.readthedocs.io/en/stable/operator-manual/cluster-bootstrapping/
- Argo CD access and operations: projects https://argo-cd.readthedocs.io/en/stable/user-guide/projects/ — RBAC https://argo-cd.readthedocs.io/en/stable/operator-manual/rbac/ — user management and SSO https://argo-cd.readthedocs.io/en/stable/operator-manual/user-management/ — notifications https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/ — triggers https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/triggers/ — templates https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/templates/ — catalog https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/catalog/ — Slack https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/services/slack/ — metrics https://argo-cd.readthedocs.io/en/stable/operator-manual/metrics/ —
argocd app rollbackhttps://argo-cd.readthedocs.io/en/stable/user-guide/commands/argocd_app_rollback/ — releases https://github.com/argoproj/argo-cd/releases - Argo CD Image Updater: overview https://argocd-image-updater.readthedocs.io/en/stable/ — update methods https://argocd-image-updater.readthedocs.io/en/stable/basics/update-methods/ — strategies https://argocd-image-updater.readthedocs.io/en/stable/basics/update-strategies/ — applications https://argocd-image-updater.readthedocs.io/en/stable/configuration/applications/ — images https://argocd-image-updater.readthedocs.io/en/stable/configuration/images/
- Flux: concepts https://fluxcd.io/flux/concepts/ — components https://fluxcd.io/flux/components/ — source https://fluxcd.io/flux/components/source/ — GitRepository https://fluxcd.io/flux/components/source/gitrepositories/ — OCIRepository https://fluxcd.io/flux/components/source/ocirepositories/ — kustomize-controller https://fluxcd.io/flux/components/kustomize/ — Kustomization https://fluxcd.io/flux/components/kustomize/kustomizations/ — helm-controller https://fluxcd.io/flux/components/helm/ — HelmRelease https://fluxcd.io/flux/components/helm/helmreleases/
- Flux notifications and images: notification-controller https://fluxcd.io/flux/components/notification/ — Alerts https://fluxcd.io/flux/components/notification/alerts/ — Providers https://fluxcd.io/flux/components/notification/providers/ — Receivers https://fluxcd.io/flux/components/notification/receivers/ — image controllers https://fluxcd.io/flux/components/image/ — ImageRepository https://fluxcd.io/flux/components/image/imagerepositories/ — ImagePolicy https://fluxcd.io/flux/components/image/imagepolicies/ — ImageUpdateAutomation https://fluxcd.io/flux/components/image/imageupdateautomations/
- Flux guides: image updates https://fluxcd.io/flux/guides/image-update/ — repository structure https://fluxcd.io/flux/guides/repository-structure/ — SOPS https://fluxcd.io/flux/guides/mozilla-sops/ — Sealed Secrets https://fluxcd.io/flux/guides/sealed-secrets/ — webhook receivers https://fluxcd.io/flux/guides/webhook-receivers/ — metrics https://fluxcd.io/flux/monitoring/metrics/ — custom metrics https://fluxcd.io/flux/monitoring/custom-metrics/ — OCI artifacts https://fluxcd.io/flux/cheatsheets/oci-artifacts/ — GitHub Action https://fluxcd.io/flux/flux-gh-action/ — FAQ https://fluxcd.io/flux/faq/
- Flux installation: bootstrap for GitHub https://fluxcd.io/flux/installation/bootstrap/github/ — multi-tenancy https://fluxcd.io/flux/installation/configuration/multitenancy/ — security https://fluxcd.io/flux/security/ —
flux installhttps://fluxcd.io/flux/cmd/flux_install/ —flux push artifacthttps://fluxcd.io/flux/cmd/flux_push_artifact/ — releases https://github.com/fluxcd/flux2/releases — Flux v1 history https://raw.githubusercontent.com/fluxcd/flux/master/README.md - CNCF: Argo graduation https://www.cncf.io/announcements/2022/12/06/the-cloud-native-computing-foundation-announces-argo-has-graduated/ — Flux graduation https://www.cncf.io/announcements/2022/11/30/flux-graduates-from-cncf-incubator/
- Kargo: docs https://docs.kargo.io/ — core concepts https://docs.kargo.io/user-guide/core-concepts/
- Progressive delivery: Argo Rollouts https://argoproj.github.io/argo-rollouts/ — Flagger https://docs.flagger.app/
- Infrastructure: Crossplane https://docs.crossplane.io/latest/whats-crossplane/ — Tofu Controller README https://raw.githubusercontent.com/flux-iac/tofu-controller/main/README.md — Tofu Controller docs https://flux-iac.github.io/tofu-controller/ — getting started https://flux-iac.github.io/tofu-controller/getting_started/
- Secrets: SOPS https://raw.githubusercontent.com/getsops/sops/main/README.rst — Sealed Secrets https://raw.githubusercontent.com/bitnami-labs/sealed-secrets/main/README.md — External Secrets Operator https://external-secrets.io/latest/
- Laravel 13: deployment (health route) https://laravel.com/docs/13.x/deployment — migrations (
--force,--isolated) https://laravel.com/docs/13.x/migrations - GitHub Actions used: checkout https://raw.githubusercontent.com/actions/checkout/main/README.md — setup-go https://raw.githubusercontent.com/actions/setup-go/main/README.md — cosign-installer https://raw.githubusercontent.com/sigstore/cosign-installer/main/README.md — Flux action https://raw.githubusercontent.com/fluxcd/flux2/main/action/README.md
- Kustomize images field: https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/images/