# GitOps in Practice: Argo CD vs Flux

> GitOps with Argo CD and Flux: repo layouts, promotion, secrets, RBAC, progressive delivery, drift, disaster recovery, and the mistakes that bite teams.

Source: https://www.derar.dev/blog/gitops-argo-cd-flux-kubernetes-delivery-2026 · Published 2026-11-11 · Updated 2026-11-14 · By Derar Sattouf

GitOps has gone from a conference slogan to the default way serious teams ship to Kubernetes. The idea is simple: the desired state of your cluster lives in Git, and software running inside the cluster continuously pulls that state and makes reality match. The hard part is everything around that sentence: how to lay out repositories, how a change travels from a pull request to production, where secrets go, who is allowed to sync what, and what happens when the cluster, the Git server, or the controller itself dies.

GitOps means four things: the desired state is declarative, versioned and immutable in Git, pulled automatically by an agent, and continuously reconciled. If one of those is missing you're doing CI/CD with extra steps, not GitOps. Pull beats push for clusters because credentials stay inside the cluster, drift is corrected rather than ignored, and a compromised CI system can't directly mutate production.

Pick Argo CD when you want a first-class UI, a central multi-cluster control plane, ApplicationSets, and an easy mental model for application teams. Pick Flux when you want a composable, Kubernetes-native toolkit, strong Helm and OCI support, built-in image automation, and no UI dependency. Either way, use two kinds of repositories: an application repo (code, Dockerfile, CI) and a config repo (manifests per environment). Don't make environments branches. Use directories and promote by pull request. Use Kustomize overlays for your own services and Helm charts for third-party software, and render and diff in CI. Promote immutable image digests or tags through environments with automated pull requests, and keep production behind a human approval.

Secrets never go to Git in plaintext. Choose SOPS (encrypt in Git), External Secrets Operator (reference a vault), or Sealed Secrets (encrypt with a cluster key), and prefer External Secrets or SOPS for new work. For tenancy, use AppProjects (Argo CD) or namespaced Kustomizations with service accounts (Flux), and keep the GitOps controller's own permissions narrow.

Add progressive delivery (Argo Rollouts or Flagger) only when you have metrics you trust, and alert on sync failures and drift, not only on pod health. Disaster recovery is "reinstall the controller and point it at Git". Test that quarterly, and back up the things Git doesn't contain: secrets keys, persistent volumes, and CRDs' external state.

A note on versions. Both projects move quickly. As of November 2026, Argo CD is in its 3.x line and Flux is in its 2.x line (Flux's image automation APIs went GA in Flux 2.7). The manifests below use stable API versions, and I flag anywhere you should check the current documentation for the API version your installed release expects. When in doubt, run `kubectl api-resources` and `kubectl explain` against your own cluster, not against a blog post.

## What GitOps actually is

The OpenGitOps working group (part of the CNCF) published four principles. They are worth memorizing because they are a precise test you can apply to any pipeline someone calls GitOps.

| Principle | Meaning | How to fail it |
|---|---|---|
| Declarative | The system is described as desired state, not as a sequence of commands | A shell script in CI that runs `kubectl apply` with ad hoc flags |
| Versioned and immutable | Desired state is stored so history is complete and tamper evident | Mutable config in a database or a UI, or force pushes to the config branch |
| Pulled automatically | An agent fetches the desired state, rather than something pushing it in | A pipeline holding cluster admin credentials |
| Continuously reconciled | The agent keeps comparing actual to desired state and corrects divergence | Applying once at deploy time and never looking again |

Everything else here is an implementation detail of these four ideas. Git isn't magic. The benefits come from properties Git happens to provide: review via pull requests, an audit log via commit history, rollback via `git revert`, and access control via branch protection.

### The mental model

```text
  Developer                    Git (config repo)                 Cluster
  ---------                    -----------------                 -------
  PR: bump image tag  ------>  main branch (approved, merged)
                                      ^                          +---------------------+
                                      | poll / webhook           | GitOps controller   |
                                      +------------------------- |  1. fetch desired   |
                                                                 |  2. render (helm/   |
                                                                 |     kustomize)      |
                                                                 |  3. diff vs live    |
                                                                 |  4. apply / prune   |
                                                                 |  5. report health   |
                                                                 +---------------------+
```

The controller is a loop. It never "finishes". That is the property that makes drift correction and disaster recovery work.

### What GitOps is not

GitOps is not a replacement for CI. CI still builds, tests, scans, and signs your image. GitOps starts at the moment a change to desired state is merged. It is also not "everything in one repo", not "Helm", and not "Argo CD". It is a pattern, and the tools implement it.

## Pull vs push, and why it matters

A traditional pipeline pushes: CI finishes, then runs `kubectl apply` or `helm upgrade` against the cluster. That requires CI to hold credentials that can change production, and the cluster has to be reachable from CI.

A GitOps pipeline pulls: CI only writes to Git (or a registry). A controller inside the cluster reads from Git and applies.

| Concern | Push (CI runs kubectl/helm) | Pull (GitOps controller) |
|---|---|---|
| Cluster credentials | Stored in CI, often cluster-admin | Never leave the cluster; controller uses in-cluster identity |
| Network exposure | API server reachable from CI runners | Outbound only from the cluster to Git/registry |
| Drift handling | None; next deploy overwrites silently | Detected continuously; optionally self-healed |
| Audit trail | CI logs, which expire | Git history, permanent and reviewable |
| Rollback | Re-run an old pipeline and hope | `git revert`, then the controller converges |
| Multi-cluster | One pipeline loop per cluster | Each cluster pulls, or one controller manages many |
| Failure mode | A failed pipeline leaves the cluster half-updated | The controller keeps retrying until converged |

Push is not wrong everywhere. For a single small cluster with a trusted team, a push pipeline with short-lived OIDC credentials is acceptable and simpler. For anything with more than a couple of environments, regulated workloads, or multiple teams, pull wins. Be honest about where you are on that spectrum.

### A hybrid that works

A common and healthy compromise: CI builds the image and **pushes a commit to the config repo** (or opens a pull request). That is "push to Git, pull to cluster". The only credential CI needs is write access to one repository path, not to the cluster.

## Argo CD vs Flux: when to pick which

Both are CNCF graduated projects. Both implement the four principles. Both can deploy plain YAML, Kustomize, and Helm. The differences are about shape and ergonomics.

### Architecture in one paragraph each

**Argo CD** is a set of services (API server, repo server, application controller, Redis, optionally Dex and the ApplicationSet controller). Its central object is the `Application` custom resource, which says "take this path of this repo at this revision, render it, and deploy it to this destination cluster and namespace". It ships a web UI and CLI, and a single Argo CD instance can manage many clusters.

**Flux** is the "GitOps Toolkit": independent controllers (source-controller, kustomize-controller, helm-controller, notification-controller, and optionally image-reflector-controller and image-automation-controller). You compose them with custom resources such as `GitRepository`, `Kustomization`, `HelmRelease`, `OCIRepository`, and `ImageUpdateAutomation`. There is no built-in UI; the community offers dashboards and Weave-style UIs, and you can lean on `flux` CLI and `kubectl`.

### Decision table

| Factor | Argo CD | Flux |
|---|---|---|
| UI | Excellent, built in; app teams love the resource tree and diff view | None built in; use CLI, Grafana, or third-party UIs |
| Multi-cluster | Hub-and-spoke from one control plane is the common model | Usually one Flux per cluster, bootstrapped from a shared repo; hub model possible |
| Fleet generation | ApplicationSets with many generators (git, cluster, list, matrix, pull request) | Kustomization plus variable substitution, one Flux per cluster, or `HelmRelease` templating |
| Helm | Renders Helm templates and applies the manifests itself (not a Helm release in the cluster by default) | Native Helm: helm-controller runs real Helm releases with history, tests, and remediation |
| Image automation | Argo CD Image Updater (separate project, check current maturity) or CI-driven commits | Built in (image-reflector and image-automation controllers, GA APIs as of Flux 2.7) |
| Progressive delivery | Argo Rollouts (same project family) | Flagger (a Flux ecosystem project) |
| Multi-tenancy | AppProjects, RBAC policies, SSO | Namespaces, service account impersonation, Kubernetes RBAC |
| Secrets | Plugins or external tools (SOPS via plugin, External Secrets) | Native SOPS decryption in kustomize-controller |
| Sync waves and hooks | Sync waves, PreSync/PostSync hooks | `dependsOn` and health checks |
| Operational model | Stateful-ish control plane to protect (Redis, repo server scaling) | Many small controllers, mostly stateless |
| Learning curve for app teams | Gentle, visual | Steeper, but very Kubernetes-idiomatic |
| Observability | Rich Prometheus metrics, notifications controller | Prometheus metrics per controller, notification controller, events |

### A practical rule of thumb

Choose **Argo CD** if the primary users are application developers who want to see their deployment, click sync, and read a diff; if you want a central place to manage dozens of clusters; or if you want ApplicationSets to stamp out apps per directory or per cluster.

Choose **Flux** if your organization is platform-engineering driven and treats the cluster as infrastructure; if you want Helm releases to behave like real Helm releases; if you want built-in SOPS and image automation; or if you want the smallest footprint and no UI to secure.

Using both is legal and occasionally sensible (for example, Flux to bootstrap the platform layer and Argo CD for application teams), but it doubles your operational surface. Do it only with a clear ownership boundary.

### Things people get wrong about this choice

- "Argo CD can't do Helm properly." It can; it simply renders with `helm template` and applies the result, so `helm list` will not show those releases. This matters if you depend on Helm hooks semantics or `helm rollback`.
- "Flux has no UI so it is immature." The lack of a bundled UI is a design choice. Teams that live in the terminal and Grafana are very happy.
- "You must pick the one with more GitHub stars." Both are healthy. Pick by team workflow.

## Repository strategies

This is where most GitOps adoptions succeed or fail.

### Two repositories, not one

| Repo | Contains | Written by | Triggers |
|---|---|---|---|
| App repo | Source code, Dockerfile, unit tests, CI workflow | Developers | CI builds and pushes an image |
| Config repo | Kubernetes manifests, Kustomize overlays, Helm values, Argo/Flux objects | Developers (via PR), CI bot, platform team | GitOps controller reconciles |

Why separate? The lifecycles differ. Config changes (scale up, change a flag) should not trigger a rebuild; code changes should not require a config review for unrelated environments. Commit noise from automated image bumps would also pollute your application history. Separating them also lets you apply different access rules: many developers can write to the app repo, while production config might require approval from a smaller group.

Small teams sometimes keep manifests in the app repo (a `deploy/` folder). That works until you have more than two environments. If you start there, keep the layout compatible so you can split later.

### Environments: directories, not branches

A branch-per-environment model (dev, staging, prod branches) looks natural and becomes a trap. Merges between branches create conflicts, hotfixes diverge, and "what is running in prod" requires comparing branches. Prefer **one branch (main), one directory per environment**, and promote by changing files in a pull request.

### Monorepo vs per-environment repos vs per-team repos

| Layout | Good for | Costs |
|---|---|---|
| One config monorepo, directory per env | Most teams under roughly 50 services; easiest promotion and review | Large blast radius for permissions; needs CODEOWNERS |
| Separate repo per environment (dev, prod) | Strict separation of prod access and audit | Promotion is cross-repo; more tooling |
| Repo per team or per app | Large orgs with strong team autonomy | Platform team must standardize bootstrapping; harder global changes |
| Platform repo plus tenant repos | Multi-tenant platforms | Needs a tenancy model (AppProjects or Flux tenancy) and onboarding automation |

My default recommendation: a single config repository with a directory per environment and CODEOWNERS rules that require platform approval for `prod/` and for `platform/`. Split only when a real constraint (compliance, team size, performance) forces you to.

### Base and overlays

For your own services, the Kustomize pattern is: a `base` that is environment agnostic and an `overlay` per environment that patches replicas, resources, hostnames, and image tags.

```text
config-repo/
├── README.md
├── CODEOWNERS
├── clusters/                      # what each cluster runs (entry points)
│   ├── dev/
│   │   ├── kustomization.yaml
│   │   └── apps.yaml              # Argo ApplicationSet or Flux Kustomization
│   ├── staging/
│   └── prod/
├── platform/                      # shared infra: ingress, cert-manager, ESO, monitoring
│   ├── base/
│   │   ├── cert-manager/
│   │   ├── external-secrets/
│   │   └── ingress/
│   └── overlays/
│       ├── dev/
│       └── prod/
├── apps/
│   ├── shop-api/
│   │   ├── base/
│   │   │   ├── deployment.yaml
│   │   │   ├── service.yaml
│   │   │   ├── hpa.yaml
│   │   │   └── kustomization.yaml
│   │   └── overlays/
│   │       ├── dev/
│   │       │   ├── kustomization.yaml
│   │       │   └── patch-replicas.yaml
│   │       ├── staging/
│   │       └── prod/
│   │           ├── kustomization.yaml
│   │           ├── patch-resources.yaml
│   │           └── pdb.yaml
│   └── shop-web/
└── tenants/                       # per-team namespaces, quotas, RBAC, AppProjects
    ├── team-payments/
    └── team-storefront/
```

Two details deserve emphasis. First, `clusters/` is the only thing a controller is bootstrapped against; everything else is reached from there. That gives you a single, auditable entry point per cluster. Second, `platform/` and `apps/` have different owners and different change velocity, so keep them in separate paths with separate approvers.

## A full working example: base and overlays

Here is a minimal but realistic service. This is the base.

```yaml
# apps/shop-api/base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-api
  labels:
    app.kubernetes.io/name: shop-api
spec:
  replicas: 2
  selector:
    matchLabels:
      app.kubernetes.io/name: shop-api
  template:
    metadata:
      labels:
        app.kubernetes.io/name: shop-api
    spec:
      securityContext:
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: api
          image: ghcr.io/example/shop-api:1.0.0
          ports:
            - name: http
              containerPort: 8080
          envFrom:
            - configMapRef:
                name: shop-api-config
            - secretRef:
                name: shop-api-secrets
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /livez
              port: http
            periodSeconds: 10
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              memory: 256Mi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
```

```yaml
# apps/shop-api/base/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - deployment.yaml
  - service.yaml
  - hpa.yaml
configMapGenerator:
  - name: shop-api-config
    literals:
      - LOG_LEVEL=info
```

The production overlay pins the image, raises replicas and resources, and adds a PodDisruptionBudget.

```yaml
# apps/shop-api/overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-prod
resources:
  - ../../base
  - pdb.yaml
patches:
  - path: patch-resources.yaml
images:
  - name: ghcr.io/example/shop-api
    newTag: 1.4.2
    # for strict immutability, prefer a digest:
    # digest: sha256:0123abcd...
configMapGenerator:
  - name: shop-api-config
    behavior: merge
    literals:
      - LOG_LEVEL=warn
```

```yaml
# apps/shop-api/overlays/prod/patch-resources.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-api
spec:
  replicas: 6
  template:
    spec:
      containers:
        - name: api
          resources:
            requests:
              cpu: 500m
              memory: 512Mi
            limits:
              memory: 512Mi
```

Notice the `images:` block in `kustomization.yaml`. That single field is what automation edits during promotion (`kustomize edit set image`), which keeps image bumps small, mechanical, and easy to review.

### Render and validate in CI before merge

Run the renderer yourself on every pull request. If it fails in CI it will fail in the cluster, only later and more embarrassingly.

```bash
# Render every overlay and schema-check it
for env in dev staging prod; do
  kustomize build apps/shop-api/overlays/$env \
    | kubeconform -strict -summary -ignore-missing-schemas -kubernetes-version 1.34.0
done

# Optional: policy checks against rendered output
kustomize build apps/shop-api/overlays/prod | conftest test --policy policy/ -
```

Set `-kubernetes-version` to the version your cluster runs. `kubeconform` skips custom resources unless you give it CRD schemas, so use `-ignore-missing-schemas` deliberately and add CRD schemas for the ones you care about.

## Argo CD in practice

### A single Application

```yaml
# clusters/prod/apps/shop-api.yaml (Argo CD Application)
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: shop-api-prod
  namespace: argocd
  finalizers:
    - resources-finalizer.argocd.argoproj.io
spec:
  project: team-storefront
  source:
    repoURL: https://github.com/example/config-repo.git
    targetRevision: main
    path: apps/shop-api/overlays/prod
  destination:
    server: https://kubernetes.default.svc
    namespace: shop-prod
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true
      - ServerSideApply=true
      - PruneLast=true
    retry:
      limit: 5
      backoff:
        duration: 10s
        factor: 2
        maxDuration: 3m
```

The finalizer makes deleting the Application also delete the resources it manages (cascading delete). That is what you want for most apps and what you must think twice about for stateful ones. `selfHeal: true` reverts manual changes; `prune: true` deletes resources that were removed from Git. Both are powerful, and both should be consciously enabled per environment (more on this in the section on drift, self-heal and pruning).

### ApplicationSets: stamp out apps from a pattern

The `ApplicationSet` controller generates Applications from generators. The most useful generator for a config repo like ours is the Git directory generator: one Application per overlay directory.

```yaml
# clusters/prod/appset-apps.yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: apps-prod
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    - git:
        repoURL: https://github.com/example/config-repo.git
        revision: main
        directories:
          - path: apps/*/overlays/prod
  template:
    metadata:
      name: '{{ index .path.segments 1 }}-prod'
    spec:
      project: default
      source:
        repoURL: https://github.com/example/config-repo.git
        targetRevision: main
        path: '{{ .path.path }}'
      destination:
        server: https://kubernetes.default.svc
        namespace: '{{ index .path.segments 1 }}-prod'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
          - CreateNamespace=true
```

Add a new directory under `apps/` and an Application appears. Remove the directory and (with the right policy) it disappears. For multi-cluster, use the `clusters` generator or a matrix of `clusters` and `git` generators so each registered cluster gets the right overlay.

A few ApplicationSet cautions: validate that the template renders for every generated parameter set (`missingkey=error` helps); remember that deleting an ApplicationSet can delete all generated Applications unless you set the appropriate `preserveResourcesOnDeletion` policy (check the current ApplicationSet docs for the exact field and behavior in your version); and gate who can create ApplicationSets, because an ApplicationSet is effectively a mass Application factory.

### App-of-apps vs ApplicationSet

| Pattern | What it is | Use when |
|---|---|---|
| App of apps | A root Application whose path contains other Application manifests | Bootstrapping, small fleets, explicit per-app customization |
| ApplicationSet | Generated Applications from generators | Many similar apps or clusters; convention over configuration |

A reasonable setup: one hand-written root Application per cluster (bootstrapped once), which deploys the ApplicationSets and AppProjects; the ApplicationSets deploy everything else.

### Sync waves and hooks

Argo CD orders resources through sync waves (the annotation `argocd.argoproj.io/sync-wave`, lower numbers first) and runs Jobs as hooks (`argocd.argoproj.io/hook: PreSync`). Use these for database migrations and CRD-before-CR ordering.

```yaml
# apps/shop-api/overlays/prod/migrate-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: shop-api-migrate
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: ghcr.io/example/shop-api:1.4.2
          command: ["node", "dist/migrate.js"]
```

Be careful: a PreSync migration that fails blocks the sync, which is usually what you want, but make sure migrations are backward compatible with the currently running version (expand-and-contract), because the old pods keep serving traffic while the new migration runs.

## Flux in practice

Flux is bootstrapped once per cluster. The command writes Flux's own manifests into your repo and then manages itself from there.

```bash
flux bootstrap github \
  --owner=example \
  --repository=config-repo \
  --branch=main \
  --path=clusters/prod \
  --personal=false
```

Check `flux bootstrap --help` for the current set of flags and authentication modes (token, SSH deploy key, GitHub App) in your version; deploy keys or GitHub App auth are preferable to personal tokens.

### Source plus Kustomization

```yaml
# clusters/prod/sources.yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: config-repo
  namespace: flux-system
spec:
  interval: 1m
  url: https://github.com/example/config-repo.git
  ref:
    branch: main
  secretRef:
    name: flux-system
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: shop-api
  namespace: flux-system
spec:
  interval: 5m
  retryInterval: 1m
  timeout: 3m
  path: ./apps/shop-api/overlays/prod
  prune: true
  wait: true
  sourceRef:
    kind: GitRepository
    name: config-repo
  targetNamespace: shop-prod
  dependsOn:
    - name: platform
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: shop-api
      namespace: shop-prod
```

`dependsOn` gives you ordering across Kustomizations (platform before apps), `wait: true` makes the Kustomization not report Ready until resources are healthy, and `prune: true` garbage collects removed resources. The `interval` is how often it reconciles even without a Git change, which is how drift gets corrected.

### Helm with HelmRelease

```yaml
# platform/base/ingress/helmrelease.yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmRepository
metadata:
  name: cert-manager
  namespace: flux-system
spec:
  interval: 1h
  url: https://charts.jetstack.io
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
  name: cert-manager
  namespace: cert-manager
spec:
  interval: 30m
  chart:
    spec:
      chart: cert-manager
      version: "1.x"
      sourceRef:
        kind: HelmRepository
        name: cert-manager
        namespace: flux-system
  install:
    crds: CreateReplace
    remediation:
      retries: 3
  upgrade:
    crds: CreateReplace
    remediation:
      retries: 3
      remediateLastFailure: true
  values:
    crds:
      enabled: true
```

Pinning a chart to a semver range like `1.x` automatically takes minor updates, which is convenient and dangerous. For production, pin an exact version and let Renovate or Dependabot open pull requests for bumps, so an upgrade is a reviewed change with a rendered diff.

### Flux and OCI

Flux can pull from OCI registries (`OCIRepository`), which lets you publish rendered or raw manifests as OCI artifacts and sync from your registry instead of Git. This is attractive when you want signed, immutable, cacheable artifacts and fewer Git API calls. The usual pattern is that CI pushes an artifact (for example with `flux push artifact`) and Flux reconciles from the registry. Verify the current `OCIRepository` API version and signature verification options against the Flux docs before adopting it.

## Kustomize vs Helm

Both are rendered by both tools. The question is which to author in.

| Question | Kustomize | Helm |
|---|---|---|
| Learning curve | Low; plain YAML plus patches | Medium; Go templates, values, chart structure |
| Best for | Your own services with a handful of environments | Distributing software to many consumers; third-party installs |
| Reviewability | Easy; diffs are plain YAML | Needs a rendered diff, since templates hide output |
| Packaging and versioning | Not a package format | Charts are versioned, published artifacts |
| Dependencies | None natively | Subcharts |
| Rollback semantics | Git revert | Git revert, plus Helm release history if the tool uses real Helm |
| Pitfalls | Patch sprawl, hard to express complex conditionals | Template logic creep, unreadable values files |

My recommendation: author internal services as Kustomize base plus overlays, consume upstream software as Helm charts with a small values file in Git, and render everything in CI. If you find yourself writing complicated conditionals in overlays, a small internal Helm chart per service archetype (web service, worker, cron) can be cleaner than copying bases.

Do not mix the two in ways that hide the final output. If you use Helm inside Kustomize (the `helmCharts` generator), make sure CI checks the rendered result, and that your GitOps tool is configured to allow it (Argo CD needs Helm enabled in its Kustomize build options; check the current documentation).

### Render diffs on pull requests

Reviewers should see the effect, not just the input. A CI job that renders base and head and posts the diff is the single highest-value GitOps quality improvement.

```bash
# In CI on a pull request
git fetch origin main
git worktree add /tmp/base origin/main

for env in dev staging prod; do
  kustomize build /tmp/base/apps/shop-api/overlays/$env > /tmp/base-$env.yaml
  kustomize build apps/shop-api/overlays/$env > /tmp/head-$env.yaml
  diff -u /tmp/base-$env.yaml /tmp/head-$env.yaml || true
done
```

Tools such as `argocd app diff --local` and `flux diff kustomization` can do cluster-aware diffs from CI, but they require cluster credentials; consider whether that defeats your push-versus-pull goals before wiring them into a general-purpose pipeline.

## Image automation and promotion across environments

How does a new image get to production? There are three common models.

| Model | How it works | Pros | Cons |
|---|---|---|---|
| CI commits to config repo | CI builds image, then runs `kustomize edit set image` and pushes or opens a PR | Explicit, works with any controller, easy approval gates | Needs a CI credential with write access to the config repo |
| Controller-based image automation | Flux image controllers (or Argo CD Image Updater) watch the registry and write back to Git | No CI coupling, tag policies (semver, regex, alphabetical) | More moving parts; commits made by a bot need review rules |
| Manual promotion PR | A human edits the tag | Maximum control | Slow, error prone |

### Recommended promotion flow

```text
  app repo                registry              config repo                      clusters
  --------                --------              -----------                      --------
  merge to main  -->  build, test, scan,  -->  bot PR: dev overlay tag   -->   dev (auto-merge)
                      sign, push image                |
                      (tag = git sha)                 v
                                              bot PR: staging overlay    -->   staging (auto-merge after dev healthy)
                                                      |
                                                      v
                                              bot PR: prod overlay       -->   prod (human approval required)
```

Rules that make this safe:

1. **Promote the same artifact.** The image that reached production must be byte-identical to the one that passed staging. Use the immutable digest, or an immutable tag convention such as the git SHA. Never rebuild per environment.
2. **Mutable tags are forbidden in prod.** `latest` or `1.4` can change under the controller's feet, and then Git no longer describes reality. Enforce it with an admission policy (Kyverno or Validating Admission Policy).
3. **Gate promotion on signals**, not time. For example, promote to prod only after staging has been healthy for a window and a smoke test passed.
4. **Keep config and image changes in separate commits** where possible so a rollback of a bad image does not undo a good config change.

### Flux image automation example

```yaml
# clusters/dev/image-automation.yaml
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImageRepository
metadata:
  name: shop-api
  namespace: flux-system
spec:
  image: ghcr.io/example/shop-api
  interval: 5m
---
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImagePolicy
metadata:
  name: shop-api
  namespace: flux-system
spec:
  imageRepositoryRef:
    name: shop-api
  filterTags:
    pattern: '^main-[a-f0-9]+-(?P<ts>[0-9]+)$'
    extract: '$ts'
  policy:
    numerical:
      order: asc
---
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImageUpdateAutomation
metadata:
  name: shop-api
  namespace: flux-system
spec:
  interval: 10m
  sourceRef:
    kind: GitRepository
    name: config-repo
  git:
    checkout:
      ref:
        branch: main
    commit:
      author:
        name: fluxbot
        email: fluxbot@example.com
      messageTemplate: 'chore(dev): update shop-api to the latest image'
    push:
      branch: main
  update:
    path: ./apps/shop-api/overlays/dev
    strategy: Setters
```

The `Setters` strategy updates fields annotated with a marker comment in your YAML, for example an `images:` entry in a Kustomization carrying a comment that points to the policy (`# {"$imagepolicy": "flux-system:shop-api:tag"}`). Check the Flux image automation guide for the exact marker syntax in your version. Use this for dev only; keep staging and prod promotion as pull requests so a human or a gate decides.

### CI-driven promotion example

```yaml
# .github/workflows/promote.yaml (in the app repo)
name: promote
on:
  workflow_run:
    workflows: [build]
    types: [completed]
    branches: [main]

jobs:
  bump-dev:
    if: github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          repository: example/config-repo
          token: ${{ secrets.CONFIG_REPO_TOKEN }}
      - name: Set image
        run: |
          cd apps/shop-api/overlays/dev
          kustomize edit set image ghcr.io/example/shop-api=ghcr.io/example/shop-api:${{ github.event.workflow_run.head_sha }}
      - name: Open PR
        uses: peter-evans/create-pull-request@v6
        with:
          branch: bot/shop-api-dev-${{ github.event.workflow_run.head_sha }}
          title: "shop-api: deploy ${{ github.event.workflow_run.head_sha }} to dev"
          commit-message: "shop-api: deploy ${{ github.event.workflow_run.head_sha }} to dev"
```

Scope `CONFIG_REPO_TOKEN` as narrowly as the platform allows, ideally a GitHub App installation token restricted to the single config repository with contents and pull-request write permission and nothing else. Pin third-party actions by commit SHA in real pipelines.

## Secrets: three workable models

Plain Kubernetes Secrets are base64 encoded, not encrypted. Committing them to Git is a breach. You need one of the following.

| Model | How it works | Pros | Cons |
|---|---|---|---|
| SOPS (with age or a cloud KMS) | Encrypt the values in YAML files; the controller decrypts at apply time | Secrets live in Git (reviewable diffs of keys, encrypted values); native in Flux | Key management is on you; Argo CD needs a plugin or tool such as KSOPS; rotating means re-encrypting files |
| External Secrets Operator (ESO) | Git holds an `ExternalSecret` that references a secret in a vault (AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, HashiCorp Vault, and others); the operator materializes a Kubernetes Secret | No secret material in Git at all; rotation happens in the vault; works identically with Argo CD and Flux | Needs a vault and its availability; one more operator |
| Sealed Secrets | A cluster-side controller holds a private key; you encrypt with `kubeseal` into a `SealedSecret` that only that cluster can decrypt | Simple; no external vault | Ciphertext is cluster-bound, so DR needs the key backed up; per-cluster re-sealing; the encryption key is a single high-value target |

### My recommendation

For most teams on a cloud provider, use **External Secrets Operator** backed by the cloud secret manager. Git contains pointers, not secrets, so a leaked repository exposes names, not values. Choose **SOPS** if you run Flux, want secrets versioned in Git, and have a KMS or age key workflow you trust. Choose **Sealed Secrets** for small clusters without a vault, but plan its key backup explicitly.

### External Secrets example

```yaml
# apps/shop-api/overlays/prod/external-secret.yaml
# apiVersion: older releases used external-secrets.io/v1beta1; verify against your installed version
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
  name: shop-api-secrets
spec:
  refreshInterval: 1h
  secretStoreRef:
    kind: ClusterSecretStore
    name: aws-secrets-manager
  target:
    name: shop-api-secrets
    creationPolicy: Owner
  data:
    - secretKey: DATABASE_URL
      remoteRef:
        key: prod/shop-api/database-url
    - secretKey: STRIPE_API_KEY
      remoteRef:
        key: prod/shop-api/stripe-api-key
```

```yaml
# platform/base/external-secrets/cluster-secret-store.yaml
apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
  name: aws-secrets-manager
spec:
  provider:
    aws:
      service: SecretsManager
      region: eu-west-1
      auth:
        jwt:
          serviceAccountRef:
            name: external-secrets
            namespace: external-secrets
```

The `jwt` auth block uses the controller's service account via IRSA (IAM Roles for Service Accounts) so there are no long-lived keys in the cluster. The equivalent exists for GCP Workload Identity and Azure Workload Identity.

### SOPS with Flux example

```yaml
# .sops.yaml at repo root
creation_rules:
  - path_regex: .*/secrets/.*\.yaml$
    encrypted_regex: '^(data|stringData)$'
    age: age1examplepublickeyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

```bash
# Generate a key pair once and store the private key safely (not in the repo)
age-keygen -o age.agekey

# Put the private key into the cluster for the Flux controller
kubectl -n flux-system create secret generic sops-age \
  --from-file=age.agekey=age.agekey

# Encrypt a secret file in place
sops --encrypt --in-place apps/shop-api/overlays/prod/secrets/db.yaml
```

```yaml
# clusters/prod/shop-api-kustomization.yaml (relevant fragment)
spec:
  decryption:
    provider: sops
    secretRef:
      name: sops-age
```

### Secret hygiene checklist

- Scan every pull request for plaintext secrets (gitleaks, trufflehog, or your platform's secret scanning with push protection).
- Never put secret values in Helm `values.yaml` in Git, even "just for dev".
- Back up the age or KMS key and the Sealed Secrets private key separately from the cluster, with restricted access and a tested restore.
- Rotate on a schedule and after any suspected exposure; with ESO, rotation is a vault change and a refresh.
- Remember Kubernetes Secrets in etcd: enable encryption at rest, and restrict `get secret` RBAC. For deeper container and cluster hardening, see the companion post on [container security hardening for Docker and Kubernetes](https://www.derar.dev/blog/container-security-hardening-docker-kubernetes-2026).

## RBAC and multi-tenancy

GitOps controllers are extremely powerful: they can create anything, anywhere they have permission. Treat them as the most privileged component in the cluster and design tenancy around that fact.

### Argo CD: AppProjects and RBAC

An `AppProject` restricts which repositories an application may deploy from, which clusters and namespaces it may deploy to, and which resource kinds it may create.

```yaml
# tenants/team-storefront/appproject.yaml
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: team-storefront
  namespace: argocd
spec:
  description: Storefront team applications
  sourceRepos:
    - https://github.com/example/config-repo.git
  destinations:
    - server: https://kubernetes.default.svc
      namespace: 'shop-*'
  clusterResourceWhitelist: []
  namespaceResourceBlacklist:
    - group: ''
      kind: ResourceQuota
    - group: ''
      kind: LimitRange
  roles:
    - name: deployer
      description: Can sync storefront apps
      policies:
        - p, proj:team-storefront:deployer, applications, sync, team-storefront/*, allow
        - p, proj:team-storefront:deployer, applications, get, team-storefront/*, allow
      groups:
        - storefront-engineers
```

An empty `clusterResourceWhitelist` means the project cannot create cluster-scoped resources (namespaces, ClusterRoles, CRDs). Quotas and limit ranges are blacklisted so tenants cannot lift their own limits. The platform team owns the `default` project settings; make sure the built-in `default` project is locked down, because by default it allows everything.

Global RBAC lives in the `argocd-rbac-cm` ConfigMap:

```yaml
# platform/base/argocd/argocd-rbac-cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-rbac-cm
  namespace: argocd
data:
  policy.default: role:readonly
  policy.csv: |
    p, role:platform-admin, applications, *, */*, allow
    p, role:platform-admin, projects, *, *, allow
    g, platform-team, role:platform-admin
  scopes: '[groups]'
```

Wire SSO (OIDC through Dex or directly to your IdP) and map IdP groups to roles. Disable the built-in `admin` account once SSO works, and avoid local users except for break-glass.

### Flux: namespaced tenants with impersonation

Flux's model leans on Kubernetes RBAC. A platform admin creates a tenant namespace, a service account, and a RoleBinding; the tenant's `Kustomization` runs as that service account.

```yaml
# tenants/team-payments/rbac.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: payments
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: payments-reconciler
  namespace: payments
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: payments-reconciler
  namespace: payments
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: edit
subjects:
  - kind: ServiceAccount
    name: payments-reconciler
    namespace: payments
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: payments
  namespace: payments
spec:
  interval: 5m
  path: ./apps/payments/overlays/prod
  prune: true
  serviceAccountName: payments-reconciler
  sourceRef:
    kind: GitRepository
    name: payments-repo
    namespace: payments
```

With `serviceAccountName`, the controller impersonates that account, so the tenant cannot create objects beyond what `edit` in their namespace allows. For stronger isolation, also enable the Flux flag that forbids cross-namespace references and set a default service account so tenants cannot omit it (see the Flux multi-tenancy lockdown docs for the exact controller flags in your version).

### Tenancy rules that hold for both tools

1. A tenant may write to **their** path in Git, and only that path (CODEOWNERS plus branch protection).
2. The GitOps controller applies tenant content with **tenant-scoped permissions**, not cluster-admin.
3. Cluster-scoped resources (CRDs, ClusterRoles, namespaces, webhooks, storage classes) are applied only from `platform/` paths owned by the platform team.
4. Add admission policy (Kyverno or ValidatingAdmissionPolicy) to enforce what RBAC cannot: no privileged pods, required resource requests, approved registries, no `latest` tags.

## Progressive delivery: Argo Rollouts and Flagger

A plain Deployment does a rolling update that stops caring once pods are Ready. Progressive delivery adds traffic shaping and automated analysis: send 5 percent, check metrics, send 25 percent, check again, and abort automatically if the error rate climbs.

| | Argo Rollouts | Flagger |
|---|---|---|
| Works with | Any GitOps tool, natural fit for Argo CD | Any GitOps tool, natural fit for Flux |
| Resource model | Replaces `Deployment` with a `Rollout` resource | Keeps your `Deployment`; adds a `Canary` resource that manages a primary copy |
| Traffic management | Service mesh, ingress controllers, Gateway API (via plugin), or replica-weighted | Service mesh, ingress, Gateway API |
| Analysis | `AnalysisTemplate` and `AnalysisRun` with Prometheus and other providers | Metric templates, webhooks, load tests |
| Strategies | Canary, blue-green | Canary, A/B, blue-green, mirroring |

### Argo Rollouts canary example

```yaml
# apps/shop-api/overlays/prod/rollout.yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: shop-api
spec:
  replicas: 6
  selector:
    matchLabels:
      app.kubernetes.io/name: shop-api
  strategy:
    canary:
      canaryService: shop-api-canary
      stableService: shop-api-stable
      trafficRouting:
        nginx:
          stableIngress: shop-api
      steps:
        - setWeight: 5
        - pause: { duration: 2m }
        - analysis:
            templates:
              - templateName: error-rate
        - setWeight: 25
        - pause: { duration: 5m }
        - setWeight: 50
        - pause: { duration: 5m }
  template:
    metadata:
      labels:
        app.kubernetes.io/name: shop-api
    spec:
      containers:
        - name: api
          image: ghcr.io/example/shop-api:1.4.2
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: error-rate
spec:
  metrics:
    - name: http-5xx-ratio
      interval: 1m
      count: 5
      failureLimit: 1
      successCondition: result[0] < 0.01
      provider:
        prometheus:
          address: http://prometheus.monitoring.svc:9090
          query: |
            sum(rate(http_requests_total{service="shop-api-canary",status=~"5.."}[2m]))
            /
            sum(rate(http_requests_total{service="shop-api-canary"}[2m]))
```

Two caveats. First, ingress-nginx, the classic traffic router for this pattern, was announced for retirement by the Kubernetes project in 2026; verify the current status and choose a Gateway API implementation or mesh for new designs. Second, Argo CD understands `Rollout` health natively, but a paused canary shows as "Progressing" until the steps finish, so tune your alerting accordingly.

### Flagger canary example

```yaml
# apps/shop-api/overlays/prod/canary.yaml
# apiVersion: verify the version your Flagger release serves (flagger.app/v1beta1 is common)
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
  name: shop-api
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: shop-api
  service:
    port: 80
    targetPort: http
  analysis:
    interval: 1m
    threshold: 5
    maxWeight: 50
    stepWeight: 10
    metrics:
      - name: request-success-rate
        thresholdRange:
          min: 99
        interval: 1m
```

### When to adopt it

Only when you have reliable request-level metrics, enough traffic to make a 5 percent canary statistically meaningful, and a rollback path your team has rehearsed. For low-traffic internal services a plain rolling update with good readiness probes and fast rollback via `git revert` is often better value.

One GitOps-specific trap: do not let `selfHeal` fight the rollout controller. Argo CD should ignore the fields the rollout controller mutates (replicas under HPA, the weights written by traffic routers). Use `ignoreDifferences` for those paths.

```yaml
# Fragment of an Argo CD Application
spec:
  ignoreDifferences:
    - group: apps
      kind: Deployment
      jsonPointers:
        - /spec/replicas
```

## Drift, self-heal, and pruning

Drift is any difference between Git and the cluster. It comes from people running `kubectl edit` during an incident, from controllers that mutate objects (HPA changing replicas, mutating webhooks adding sidecars, cert-manager writing annotations), and from operators that legitimately own fields.

### Policy matrix

| Setting | Argo CD | Flux | Recommended default |
|---|---|---|---|
| Automatic sync of new commits | `syncPolicy.automated` | Kustomization reconciles on interval or webhook | On for dev and staging; on for prod if protected by PR approval |
| Revert manual changes | `selfHeal: true` | Always on; reapplies each interval | On everywhere; use break-glass suspend during incidents |
| Delete removed resources | `prune: true` | `prune: true` | On, with `PruneLast` or equivalent for ordering; protect stateful resources |
| Ignore controller-managed fields | `ignoreDifferences` | Server-side apply field ownership, `kustomize.toolkit.fluxcd.io/reconcile: disabled` annotation per object | Configure for HPA replicas and webhook-injected fields |

### Protect stateful and dangerous resources

Pruning is how a typo becomes an outage. Protect PersistentVolumeClaims, databases managed by operators, and namespaces.

```yaml
# Argo CD: prevent pruning of a specific resource
metadata:
  annotations:
    argocd.argoproj.io/sync-options: Prune=false
```

```yaml
# Flux: prevent pruning and further reconciliation of a specific resource
metadata:
  annotations:
    kustomize.toolkit.fluxcd.io/prune: disabled
```

### The incident break-glass procedure

During an incident someone must be able to change the cluster by hand without the controller undoing it every minute. Make that explicit and time-limited.

```bash
# Flux: pause reconciliation of one Kustomization
flux suspend kustomization shop-api -n flux-system
# ... fix things by hand ...
flux resume kustomization shop-api -n flux-system

# Argo CD: disable automated sync for one app
argocd app set shop-api-prod --sync-policy none
# ... fix things by hand ...
argocd app set shop-api-prod --sync-policy automated --self-heal --auto-prune
```

Then **commit the fix to Git** before resuming. If you forget, the controller will revert your fix at the next reconcile. Put this procedure in your runbook and alert on any Application or Kustomization that stays suspended longer than a set threshold.

## Disaster recovery

GitOps makes recovery dramatically simpler, because the cluster is cattle. But "everything is in Git" is never fully true. List what is not.

| Asset | In Git? | Recovery plan |
|---|---|---|
| Kubernetes manifests | Yes | Reinstall controller, point at repo |
| Controller bootstrap config | Mostly (Flux writes it back; Argo CD needs a bootstrap script or Helm values) | Keep a documented, tested bootstrap command |
| Secrets (ESO) | No, only references | Restore the vault; check IAM trust relationships and cluster identity |
| SOPS or Sealed Secrets keys | No, by design | Back up private keys offline; test decryption in a scratch cluster |
| Persistent volumes and databases | No | Volume snapshots, database backups, Velero or cloud-native backup |
| CRD-backed external state (cloud resources from Crossplane, DNS records) | Declared in Git, state lives outside | Understand adoption versus recreate behavior before restoring |
| Argo CD cluster registrations and repo credentials | Not automatically | Declare them as Secrets (via ESO) or script them |
| Git itself | It is the single source of truth | Mirror the repo; treat Git outage as a degraded mode (controllers keep running the last state) |

### A concrete recovery drill

1. Create a brand new cluster in the same cloud account (Terraform or your cluster API tooling).
2. Install the GitOps controller using the documented bootstrap command pointing at `clusters/prod`.
3. Restore the secrets key material (age key, or ensure the new cluster's identity can reach the vault).
4. Watch controllers converge: `flux get kustomizations -A --watch` or `argocd app list`.
5. Restore data from backups (volume snapshots, database point-in-time recovery).
6. Cut over DNS or the load balancer.
7. Record the elapsed time. That number is your real recovery time objective.

Run this quarterly into a scratch environment. Teams that have never done it discover that a Sealed Secrets key was never backed up, or that a CRD must be installed before the CR that uses it, at the worst possible moment.

### Ordering and bootstrapping pitfalls

CRDs must exist before the resources that use them. In Flux, split CRD-installing HelmReleases or Kustomizations into an earlier layer and use `dependsOn`. In Argo CD, use sync waves or separate Applications, and consider `SkipDryRunOnMissingResource=true` for the first sync of custom resources whose CRDs are installed in the same sync.

### What happens when Git is down

Both controllers keep the last known state running; nothing is deleted because Git is unreachable. You lose the ability to deploy changes until it returns. Mitigate with a read mirror and, for critical paths, the ability to temporarily point the controller at the mirror.

## Observability of sync

GitOps adds a new failure domain: the controller. Pods can be perfectly healthy while the controller has been failing to sync for three days. Monitor the pipeline itself.

### What to watch

| Signal | Why | Argo CD source | Flux source |
|---|---|---|---|
| Sync failure | A merged change did not apply | `argocd_app_info` with sync status and operation phase labels | `gotk_reconcile_condition` for Ready false |
| Out of sync duration | Drift or a stuck change | `argocd_app_info` with sync_status OutOfSync | `gotk_resource_info` and condition metrics |
| Health degraded | App deployed but unhealthy | health_status label on `argocd_app_info` | Kustomization health checks, `HelmRelease` Ready |
| Reconcile latency | Controller overload | `argocd_app_reconcile` histogram | `gotk_reconcile_duration_seconds` |
| Repo fetch errors | Git credentials expired, rate limits | repo server request and error metrics | source-controller condition and events |
| Suspended objects | Someone forgot to resume | Application with automated sync disabled | `gotk_suspend_status` |

Metric names evolve, so confirm them in your controller's `/metrics` endpoint. Example alert rules (shown as plain text since they are PromQL):

```text
# Argo CD: app out of sync for more than 30 minutes
argocd_app_info{sync_status="OutOfSync"} == 1   for: 30m

# Argo CD: app degraded
argocd_app_info{health_status="Degraded"} == 1   for: 10m

# Flux: reconciliation failing
gotk_reconcile_condition{type="Ready", status="False"} == 1   for: 15m

# Flux: object suspended for more than 4 hours
gotk_suspend_status == 1   for: 4h
```

### Notifications

Both tools can notify chat and Git providers, and the most valuable notification is the commit status: show on the pull request or commit whether it actually synced and became healthy.

```yaml
# Flux notification: Slack provider and alert
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Provider
metadata:
  name: slack
  namespace: flux-system
spec:
  type: slack
  channel: deployments
  secretRef:
    name: slack-webhook
---
apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Alert
metadata:
  name: failures
  namespace: flux-system
spec:
  providerRef:
    name: slack
  eventSeverity: error
  eventSources:
    - kind: Kustomization
      name: '*'
    - kind: HelmRelease
      name: '*'
```

The notification API version has changed across Flux releases, so verify the current one with `kubectl api-resources | grep notification`. For Argo CD, configure the notifications controller with triggers such as `on-sync-failed` and `on-health-degraded` and subscribe applications through annotations.

### Correlate deploys with metrics

Annotate dashboards with sync events (Grafana annotations from Argo CD or Flux webhooks) so when latency jumps you can see which commit landed at that moment. Add the Git SHA as a label on workloads (`app.kubernetes.io/version`) and in your tracing resource attributes. Event-driven teams can also publish deploy events to their broker; see [event-driven architecture with outbox and idempotency](https://www.derar.dev/blog/event-driven-architecture-outbox-idempotency-2026) for the delivery guarantees to expect when you do.

## Lab: build the pipeline end to end

Time: about two hours with a local cluster. You will use `kind` for the cluster and Flux for the controller; the same steps map to Argo CD with the manifests above.

**Step 1: create the cluster and repo.**

```bash
kind create cluster --name gitops-lab
gh repo create gitops-lab-config --private --clone
cd gitops-lab-config
mkdir -p clusters/dev apps/hello/base apps/hello/overlays/dev
```

**Step 2: author the base and the dev overlay** (a Deployment, a Service, and a Kustomization as in the full working example earlier).

**Step 3: bootstrap Flux** against the repo.

```bash
export GITHUB_TOKEN=<token-with-repo-scope>
flux check --pre
flux bootstrap github --owner=<you> --repository=gitops-lab-config \
  --branch=main --path=clusters/dev --personal
```

**Step 4: add a Kustomization for the app** in `clusters/dev/`, commit, push, and watch it converge.

```bash
flux get kustomizations --watch
kubectl -n hello get pods
```

**Step 5: prove drift correction.** Scale the Deployment manually and watch Flux revert it.

```bash
kubectl -n hello scale deploy/hello --replicas=5
sleep 90
kubectl -n hello get deploy hello   # back to the Git value
```

**Step 6: prove rollback.** Merge a bad image tag, observe the failure in `flux get kustomizations` and events, then `git revert` and watch it recover.

**Step 7: add secrets.** Install External Secrets with a fake provider, or use SOPS with an age key, and mount a secret in the Deployment. Confirm the repo contains no plaintext.

**Step 8: add the PR render-diff job** from the Kustomize vs Helm section and make it required via branch protection.

**Step 9: delete the cluster and rebuild it** from the repo alone. Time it. That is your disaster recovery drill in miniature.

### Production readiness checklist

- [ ] Config repo has branch protection, required reviews, and CODEOWNERS for `prod/` and `platform/`.
- [ ] CI renders and schema-validates every overlay on every pull request.
- [ ] Image references in prod are immutable (digest or unique tag); an admission policy blocks `latest`.
- [ ] No plaintext secrets in Git; secret scanning with push protection is on.
- [ ] Controller identity has the minimum permissions; tenants are isolated (AppProjects or service account impersonation).
- [ ] Built-in admin accounts are disabled; SSO is configured.
- [ ] Alerts exist for sync failure, prolonged OutOfSync, degraded health, suspended objects, and repo fetch errors.
- [ ] A documented break-glass procedure exists and is time limited.
- [ ] Backups cover volumes, databases, and secret keys, and a full rebuild drill has been timed this quarter.
- [ ] Prune protection is set on stateful resources.
- [ ] Controllers are pinned to a version and upgraded through a PR with a changelog review.

Measure success by boring outcomes. Can a new engineer ship a change without cluster credentials? Can you answer "what is running in production" with a single path in Git? Can you rebuild the cluster from nothing in an hour and prove it with a timed drill? If not, that's the gap to close first.

## Where this usually goes wrong

1. Branch per environment. It produces merge conflicts and ambiguity. Use directories on one branch.
2. Mutable image tags. If `1.4` can change, Git no longer describes the cluster. Use digests or unique tags.
3. Rebuilding for each environment. You must promote the artifact that was tested, not a new build.
4. Committing secrets "temporarily". Git history is forever. Assume a leaked secret is compromised and rotate it.
5. Giving the controller cluster-admin to everyone's apps. One bad manifest from one team can then modify anything. Scope with AppProjects or impersonation.
6. Leaving Argo CD's `default` project open. It allows all repos, clusters, and resources.
7. Enabling prune without protecting stateful resources. Deleting a manifest should never delete a database volume.
8. Fighting other controllers. HPA, VPA, service meshes, and mutating webhooks change fields; configure `ignoreDifferences` or server-side apply instead of living with a permanent OutOfSync state that everyone learns to ignore.
9. Ignoring the controller's own health. No alerts on reconcile failures means silent staleness.
10. One giant Application or Kustomization. A single failing resource blocks everything and the blast radius is the whole cluster. Split by ownership and by dependency layer.
11. Skipping render validation in CI. Finding a template error in the cluster is slow and noisy.
12. Automated sync to prod with no approval gate and no progressive delivery. Automation without guardrails is just faster outages.
13. Treating Helm values as an unreviewable blob. Diff the rendered output on pull requests.
14. No bootstrap documentation. The first time you need it should not be during an outage.
15. Sync waves and hooks for everything. They are for ordering and migrations. If every resource has a wave, you have reinvented a fragile imperative script.

## When GitOps isn't worth it

- One service, one server, one developer. A managed platform (Cloud Run, Fly, a PaaS) and a CI pipeline will cost you far less than operating a controller and a config repo.
- No Kubernetes. The tools here reconcile Kubernetes objects. For VMs and cloud resources, use Terraform or OpenTofu with a plan and apply workflow, or Crossplane if you want Kubernetes-style reconciliation of cloud APIs.
- Highly dynamic, runtime-generated resources. If your application creates Kubernetes objects at runtime (per-tenant jobs, preview environments), those belong to the application, not to Git. Use GitOps for the operator and templates, not for each generated instance.
- Frequent, ephemeral, human-driven experimentation. Data scientists iterating in notebooks do not want a pull request per change. Give them a sandbox namespace outside the reconciled tree.
- No review culture. GitOps amplifies your process. If nobody reviews pull requests, you have automated an unreviewed deployment path.
- Teams who cannot yet operate a cluster. GitOps does not simplify Kubernetes; it organizes change to it. Learn the basics first (see the companion post on Kubernetes for application developers).

## Questions that come up

**Can I use Argo CD and Flux together?** Yes, but you double the operational surface. A defensible split is Flux for cluster platform components and Argo CD for application teams. Define which tool owns which namespaces so they never fight over the same objects.

**Should the controller auto-sync production?** If production changes require an approved pull request and you have health gates and rollbacks, automatic sync is fine and removes a manual step. If your process lets unreviewed changes reach `main`, require manual sync until it does not.

**How do I roll back?** Revert the commit and let the controller converge. Do not use the UI "rollback" as your main mechanism, because it leaves Git and the cluster disagreeing (and with self-heal on, it may be undone).

**How often should controllers poll?** Typical intervals are 1 to 5 minutes for Git, longer for Helm repositories. Prefer webhooks from your Git provider for latency, and keep polling as a safety net.

**How many Applications can Argo CD handle?** It scales to thousands with tuning (sharding the application controller, scaling the repo server, using manifest-generate-paths annotations to avoid re-rendering on unrelated commits). Check the current high-availability and scaling documentation for settings in your version.

**What about preview environments per pull request?** Argo CD's ApplicationSet has a pull request generator for exactly this. With Flux, teams typically template a Kustomization per branch via CI. Set a TTL and quota so previews do not accumulate.

## Sources and docs

- [OpenGitOps principles](https://opengitops.dev/)
- [Argo CD documentation](https://argo-cd.readthedocs.io/)
- [Argo CD ApplicationSet documentation](https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/)
- [Argo Rollouts documentation](https://argo-rollouts.readthedocs.io/)
- [Flux documentation](https://fluxcd.io/flux/)
- [Flux multi-tenancy guide](https://fluxcd.io/flux/installation/configuration/multitenancy/)
- [Flux image automation guide](https://fluxcd.io/flux/guides/image-update/)
- [Flagger documentation](https://docs.flagger.app/)
- [External Secrets Operator](https://external-secrets.io/)
- [SOPS](https://getsops.io/)
- [Sealed Secrets](https://github.com/bitnami-labs/sealed-secrets)
- [Kustomize documentation](https://kubectl.docs.kubernetes.io/references/kustomize/)
- [kubeconform](https://github.com/yannh/kubeconform)
- Related on this site: [container security hardening for Docker and Kubernetes](https://www.derar.dev/blog/container-security-hardening-docker-kubernetes-2026) and [event-driven architecture, outbox, and idempotency](https://www.derar.dev/blog/event-driven-architecture-outbox-idempotency-2026).
