Shelves / DevOps, CI/CD and IaC
DL·95
GitOps
GitOps as an operating model: the OpenGitOps principles (declarative, versioned and immutable, pulled automatically, continuously reconciled), push versus pull delivery, drift detection and self-healing, repository and environment layouts, promotion between environments, secrets, and ordering; Argo CD in depth (Applications, Projects, sync policies, waves and hooks, health, ApplicationSets, multi-cluster, RBAC); Flux in depth (sources, Kustomizations, HelmReleases, image automation, SOPS); GitOps for infrastructure; and where GitOps stops.
Start here: the cluster pulls its state from Git
Push versus pull
In the Start Here pipeline, CI pushed changes into the cluster (kubectl set image …), so CI needed cluster credentials, and what ran depended on which pipeline ran last. GitOps reverses the direction: a Git repository holds the complete desired state of the environment, and an agent inside the cluster continuously pulls it and makes the cluster match. Four principles (from the OpenGitOps project): the desired state is declarative, versioned and immutable (in Git), pulled automatically, and continuously reconciled.
Watching it work
The repository holds one manifest: a Deployment of 2 tiffin pods running VERSION=v1, and a Service. Start the reconciler, then change things only through Git:
reconciler started (every 3 s: fetch Git, apply, prune)
first sync: deployment ready after 1.7 s
$ (edit apps/menu.yaml: VERSION v1 → v2); git commit -am "menu v2"; git push
the cluster runs v2 on all pods after 4.7 s (no kubectl command run by anyone)
$ kubectl scale deploy menu --replicas=5 # a manual change: drift
replicas now: 5
reverted to Git's 2 replicas after 0.8 s
$ git revert --no-edit HEAD; git push # roll back by reverting the commit
back on v1 after 4.6 s
$ git log --oneline # the audit trail of what ran when
a546a8e Revert "menu v2"
8d3ec93 menu v2
b1807cd menu service v1
A deploy was a commit; a rollback was a revert; and a manual kubectl scale didn't stick, because the next reconciliation re-applied Git's declared 2 replicas. The Git log is now an exact, reviewed history of every change to the environment, and recreating the environment (after a cluster loss, or for a new region) means pointing a fresh agent at the same repository.
What it changes in practice
| Push (CI deploys) | Pull (GitOps agent) | |
|---|---|---|
| Who holds cluster credentials | The CI system | Only the in-cluster agent |
| Source of truth | Whatever ran last | The Git repository |
| Manual changes | Persist silently (drift) | Detected and reverted (or reported) |
| Rollback | Re-run an old pipeline | git revert |
| Audit | CI logs | Git history plus pull request reviews |
| CI's job | Build, test, deploy | Build, test, publish, then open a PR changing the image tag in Git |
Argo CD (with its UI, applications and sync waves) and Flux (a set of composable controllers) are the two CNCF-graduated GitOps tools; both add health assessment, multi-cluster management, Helm and Kustomize rendering, notifications and image-update automation.
How deep to go in GitOps
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain GitOps principles and push versus pull delivery |
| L2 | Run Argo CD or Flux for an application with Kustomize or Helm and automated sync |
| L3 | Explain reconciliation, drift handling, pruning, sync ordering and secrets approaches |
| L4 | Diagnose stuck syncs, drift loops, conflicting controllers and failed health checks |
| L5 | Design repository layout, environment promotion and multi-cluster delivery |
| L6 | Operate GitOps for many teams and clusters with policy, tenancy and progressive delivery |
What GitOps is
Volume 6 (ch. 83) introduced GitOps for Kubernetes deployments. This chapter goes deeper. The term was coined by Weaveworks in 2017; the CNCF OpenGitOps project standardised four principles:
| Principle | Meaning |
|---|---|
| Declarative | The desired state of the system is expressed declaratively (manifests, Helm values, Kustomize overlays, Crossplane claims) |
| Versioned and immutable | Desired state is stored in a way that enforces immutability and versioning, and keeps a complete history (Git, or OCI artefacts) |
| Pulled automatically | Software agents automatically pull the desired state from the source |
| Continuously reconciled | Agents continuously observe actual state and attempt to apply the desired state, detecting and correcting drift |
In other words, GitOps applies the Kubernetes controller pattern (Vol. 6 ch. 83) to delivery itself: Git holds the spec, a controller in the cluster reconciles reality toward it, and every change to production is a commit.
Push versus pull delivery
| Push (CI applies) | Pull (GitOps agent) | |
|---|---|---|
| Credentials | CI needs cluster admin credentials, a juicy target | Agent runs inside the cluster with its own service account; CI only needs write access to the config repo |
| Network | CI must reach the cluster API | Cluster only needs outbound access to Git/registries (works for private and edge clusters) |
| Drift | Undetected until the next deploy | Continuously detected; optionally auto-corrected |
| Audit | Pipeline logs | Git history is the deployment log |
| Disaster recovery | Re-run all pipelines | Point a new cluster at the repo |
| Multi-cluster | One pipeline step per cluster | Agents (or a central Argo CD) reconcile many clusters |
Desired state, reconciliation and drift
The reconcile loop, concretely:
- Fetch the desired state: a Git commit (or OCI artefact), rendered with Kustomize or Helm into plain manifests.
- Compare with live objects in the cluster (using server-side apply dry runs or structured diffs, ignoring fields controllers set, like
statusor HPA-managedreplicas). - Report status: Synced / OutOfSync (does live match desired?) and Healthy / Progressing / Degraded (are the resources actually working?).
- Apply changes (automatically or on approval), optionally pruning objects removed from Git.
- Repeat on a schedule (Argo CD's default refresh is about every 3 minutes) and on webhooks from Git.
Drift is any difference between live and desired state: someone ran kubectl edit, an operator mutated a field, a resource was deleted by hand. Options:
- Detect and alert only (sync manually): safest for sensitive resources.
- Self-heal: the agent reverts manual changes automatically. Strong guarantee that Git is the truth; surprising for engineers who try a quick fix in production (it'll be undone within minutes, which is the point).
- Ignore specific fields that other controllers legitimately own (
spec.replicaswhen an HPA manages it, injected sidecar annotations, webhook CA bundles).
Repository design
App repo versus config repo
- Application repository: source code, Dockerfile, tests, and (often) the base manifests or Helm chart.
- Configuration (environment) repository: what runs where: per-environment overlays and image digests. CI updates it via commits or pull requests.
Separating them keeps deployment history clean (config commits = deployments), lets platform teams review environment changes, and avoids CI loops (a commit to the app repo triggering CI that commits to the same repo). Small teams can start with one repo and a deploy/ directory.
Environments: directories, not branches
platform-config/
├── apps/
│ └── orders/
│ ├── base/ # Deployment, Service, HPA, PDB
│ └── overlays/
│ ├── dev/ # kustomization.yaml: image digest, replicas: 1
│ ├── staging/
│ └── prod/ # replicas: 6, zone spread, prod config
├── infrastructure/
│ ├── cert-manager/
│ ├── external-secrets/
│ └── gateway/
└── clusters/
├── prod-ap-south-1/ # what this cluster runs (Argo CD apps or Flux Kustomizations)
└── staging-ap-south-1/
Avoid one branch per environment (merging dev → staging → prod branches): merges carry unintended changes, environment-specific differences cause endless conflicts, and it's hard to see what differs between environments. Directory per environment on one branch makes differences explicit (diff two overlay folders), and promotion becomes a small, reviewable change: copy the image digest (and any config) from staging/ to prod/.
Promotion
Promotion between environments in GitOps is a commit:
- CI builds the image and opens a PR (or commits) updating
overlays/devwith the new digest. - After dev checks pass, an automated job or a person opens a PR updating
overlays/stagingwith the same digest. - Production promotion requires review/approval (CODEOWNERS on
overlays/prod), then merges.
Tools that automate this: Argo CD Image Updater and Flux image automation (watch registries and commit new tags or digests matching a policy), Kargo (Akuity; models stages and promotion pipelines with verification on top of Argo CD), Renovate, or custom CI jobs. Progressive delivery (Argo Rollouts, Flagger) then controls how a promoted version reaches users within an environment (Vol. 6 ch. 84).
Argo CD
Argo CD (Intuit, CNCF graduated; version 3.5 as of autumn 2026) is a GitOps controller with a rich web UI, CLI and API.
Core objects
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: orders-prod
namespace: argocd
finalizers: [resources-finalizer.argocd.argoproj.io] # delete resources when the app is deleted
spec:
project: shop
source:
repoURL: https://github.com/acme/platform-config.git
targetRevision: main
path: apps/orders/overlays/prod # Kustomize detected automatically
destination:
server: https://kubernetes.default.svc # or another registered cluster
namespace: shop
syncPolicy:
automated:
prune: true # delete resources removed from Git
selfHeal: true # revert manual drift
syncOptions:
- CreateNamespace=true
- ServerSideApply=true
- PruneLast=true
retry: { limit: 5, backoff: { duration: 10s, factor: 2, maxDuration: 3m } }
ignoreDifferences:
- group: apps
kind: Deployment
jsonPointers: [/spec/replicas] # owned by the HPA
- Application: one source (Git path, Helm chart, OCI artefact; or multiple sources, e.g. a chart from one repo with values from another) → one destination (cluster + namespace).
- AppProject: a security boundary: which repos an app may use, which clusters/namespaces it may deploy to, which resource kinds are allowed (e.g. teams may not create
ClusterRoles), sync windows (no deployments on Friday evenings), and roles for RBAC. - Sync status (Synced/OutOfSync) and health status (Healthy/Progressing/Degraded/Suspended/Missing), with built-in health checks for standard kinds and custom Lua health checks for CRDs.
Ordering: sync waves and hooks
Argo CD applies resources in a defined order: by phase (PreSync → Sync → PostSync, plus SyncFail and PostDelete), then by sync wave (annotation argocd.argoproj.io/sync-wave: "-1", lower first), then by kind (Namespaces and CRDs before the resources that use them). Each wave must be healthy before the next starts.
apiVersion: batch/v1
kind: Job
metadata:
name: orders-db-migrate
annotations:
argocd.argoproj.io/hook: PreSync # run before the new version syncs
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: ghcr.io/acme/orders-migrations@sha256:…
args: ["migrate", "--to", "latest"]
Use hooks sparingly and make them idempotent; schema migrations must follow expand/contract rules (chapter 96) because a PreSync hook runs while the old version is still serving.
Scaling out: ApplicationSets, App of Apps, multi-cluster
- App of Apps: an Application whose manifests are other Applications: bootstrap a whole cluster from one root app.
- ApplicationSet: a template that generates Applications from generators:
- list (explicit entries)
- cluster (every registered cluster matching labels)
- git (one app per directory or per config file)
- matrix/merge (combinations)
- pull request (preview environments per open PR)
- SCM provider (one per repository in an organisation)
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata: { name: orders, namespace: argocd }
spec:
goTemplate: true
generators:
- matrix:
generators:
- clusters: { selector: { matchLabels: { env: prod } } } # every prod cluster
- list: { elements: [{ app: orders }, { app: payments }] }
template:
metadata: { name: "{{.app}}-{{.name}}" }
spec:
project: shop
source:
repoURL: https://github.com/acme/platform-config.git
targetRevision: main
path: "apps/{{.app}}/overlays/prod"
destination: { server: "{{.server}}", namespace: shop }
syncPolicy: { automated: { prune: true, selfHeal: true } }
- Multi-cluster: one central Argo CD managing many clusters (convenient, but a single high-value target holding credentials to all clusters), or an Argo CD per cluster (more isolation, more to operate); hybrids exist (agent-based models such as the Argo CD agent project, Akuity's managed offering).
- Security: SSO (OIDC/Dex), RBAC policies per project, no admin account in production, restrict who can create Applications pointing at arbitrary repos, keep Argo CD itself up to date (it has had serious CVEs), and run
argocd-repo-serverwith care (it renders untrusted Helm/Kustomize/plugins). - Notifications (Slack, Teams, webhooks) on sync and health changes; metrics for Prometheus.
Flux
Flux (Weaveworks, CNCF graduated; Flux 2.x) is a set of composable controllers with no central UI by default (UIs exist: Weave GitOps successors, Capacitor, Headlamp plugins), configured entirely with Kubernetes custom resources:
| Controller | Resources | Role |
|---|---|---|
| source-controller | GitRepository, OCIRepository, HelmRepository, HelmChart, Bucket |
Fetch and verify sources (including cosign/Notation signature verification of OCI artefacts and commit signature checks) and expose them as artefacts |
| kustomize-controller | Kustomization |
Build and apply manifests from a source path, with pruning, health checks, dependsOn, and SOPS decryption |
| helm-controller | HelmRelease |
Install, upgrade, test and roll back Helm releases declaratively, with drift detection |
| notification-controller | Provider, Alert, Receiver |
Outbound alerts (Slack, Teams, Git commit statuses) and inbound webhooks to trigger reconciliation |
| image-reflector / image-automation | ImageRepository, ImagePolicy, ImageUpdateAutomation |
Scan registries, select tags by policy (semver, regex), commit updates back to Git |
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata: { name: platform-config, namespace: flux-system }
spec:
interval: 1m
url: https://github.com/acme/platform-config
ref: { branch: main }
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata: { name: infrastructure, namespace: flux-system }
spec:
interval: 10m
sourceRef: { kind: GitRepository, name: platform-config }
path: ./infrastructure
prune: true
wait: true # wait for resources to become ready
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata: { name: orders-prod, namespace: flux-system }
spec:
interval: 5m
dependsOn: [{ name: infrastructure }] # CRDs, cert-manager, gateway first
sourceRef: { kind: GitRepository, name: platform-config }
path: ./apps/orders/overlays/prod
prune: true
decryption: { provider: sops, secretRef: { name: sops-age } }
healthChecks:
- { apiVersion: apps/v1, kind: Deployment, name: orders, namespace: shop }
Flux versus Argo CD in short: both are mature CNCF graduated projects that reconcile Git (and OCI) into clusters. Argo CD offers a strong UI, application-centric model, ApplicationSets and centralised multi-cluster management; Flux is Kubernetes-native and composable (everything is a CRD, no separate API server or UI to secure), with excellent Helm and OCI support, and fits platform teams who build their own abstractions. Many organisations pick based on whether developers want the UI.
Secrets in GitOps
Git must not contain plaintext secrets. Options:
| Approach | How | Notes |
|---|---|---|
| SOPS (with age, KMS, Vault keys) | Encrypt values inside YAML files; Flux decrypts natively; Argo CD via plugins (KSOPS) | Secrets versioned with config; key management needed |
| Sealed Secrets (Bitnami) | Encrypt with a cluster's public key into a SealedSecret that only the controller in that cluster can decrypt |
Simple; tied to cluster keys (back them up) |
| External Secrets Operator | Git holds an ExternalSecret reference; the operator fetches values from AWS Secrets Manager, Vault, GCP/Azure secret stores |
The common production choice: rotation in the secret store, no secret material in Git at all |
| Secrets Store CSI Driver | Mount secrets from external stores as volumes | Avoids Kubernetes Secret objects entirely (optionally syncs them) |
GitOps beyond applications
- Cluster add-ons and platform: ingress/gateway controllers, cert-manager, observability agents, policy engines, all reconciled from the same repo (the "infrastructure" layer before apps).
- Cloud infrastructure: Crossplane (cloud resources as Kubernetes objects reconciled continuously), AWS Controllers for Kubernetes (ACK), Azure Service Operator, Config Connector; or Terraform/OpenTofu run by GitOps controllers (Flux's tofu-controller, Atlantis/HCP Terraform VCS-driven runs).
- Configuration for non-Kubernetes targets is possible but less natural; VCS-driven Terraform pipelines give a GitOps-like workflow without a continuous reconciler.
Where GitOps stops
GitOps is excellent for desired state, and awkward for procedures:
- Ordering across systems (migrate the database, then deploy, then flip a flag) needs hooks, waves,
dependsOn, or orchestration outside GitOps. - Imperative operations (restart a pod, run a one-off job, failover a database) don't fit "state in Git"; use runbooks, operators or controlled tooling, and record them.
- Secrets and dynamic values come from outside Git.
- Feedback to the developer: the PR is merged before the deployment happens, so surface sync and health results back (commit statuses, notifications, dashboards).
- Large monorepos of manifests can make reconciliation slow; split by team, cluster or layer.
- Emergency changes: decide the break-glass process (pause auto-sync, change, then commit the fix so Git catches up).
Lab: pruning, broken commits, secrets and drift windows
The chapter's minigitops reconciler (server-side apply with forced ownership, owner-labelled pruning, SOPS 3.11 with age 1.2 keys) against the k3s 1.37 cluster; a bare Git repository on the same machine plays GitHub.
Experiment 1: deletion is part of desired state
configmap created after 1.6 s
configmap deleted after 3.7 s
Adding a manifest created the object; removing the file from Git removed it from the cluster. Without pruning, deleted manifests leave orphans that nobody owns and nobody can explain six months later. Pruning must be scoped to what the agent owns (here a label; Argo CD tracks resources by an application label or annotation, Flux by inventory), or a misconfigured agent could delete things it never created. Argo CD makes pruning opt-in for this reason.
Experiment 2: a broken commit
A typo (replicas: two) pushed to main:
05:59:48 rev 69d71b4: apply FAILED, cluster left as it was: Error from server: failed to create typed patch object (default/menu; apps/v1, Kind=Deployment): .spec.replicas: expected numeric (int or fl…
cluster still runs: replicas=2, ready=2
05:59:52 rev 50eee4b: synced (2 objects)
The API server rejected the invalid manifest, so nothing changed and the reconciler reported the failure; reverting the commit synced cleanly. Don't rely on the cluster to catch mistakes, though: validate manifests in CI before merge (kubeconform, kustomize build, policy checks), because a valid but wrong change (an image that crashes, a deleted Service) would sync perfectly. Real GitOps tools add health assessment (did the rollout become healthy?) and notifications.
Experiment 3: secrets in Git, encrypted
what Git stores:
kind: Secret
api_key: ENC[AES256_GCM,data:QaX/GjcHuW609rAgxAJhsFQCKPCP,iv:9mSHCY67Q6UXf9NjsCu9MnKhBuMKgPMakMoF5K3ILjM=,…
- recipient: age14w42xrdxsfs2rvs6x8k7rqn7d4aflww2zt7g7aplw4qwtn9paegq2ncglz
-----BEGIN AGE ENCRYPTED FILE-----
what the cluster has: api_key=pk_live_51Hx9T2tiffin
grep for the key in the Git repository's history: 0 matches
SOPS encrypted only the secret values (keys and structure stay readable, so diffs and reviews still work), for the age public key of the cluster's agent; only the agent's private key can decrypt. The plaintext never touched Git. Alternatives: Sealed Secrets (encrypt to a controller's key), or keep secrets out of Git entirely and reference them from a secret manager with the External Secrets Operator. Whichever you use, the private key or secret-store access becomes the crown jewel.
Experiment 4: how long drift survives
A manual kubectl scale three times, with the reconciler on two intervals:
sync interval 3 s: manual change reverted after 0.6 1.9 2.0 s
sync interval 30 s: manual change reverted after 27.4 29.5 29.0 s
Drift lasted up to one sync interval. Real tools combine periodic resyncs (Argo CD defaults to about 3 minutes; Flux intervals are per object) with watches that react to changes immediately, and webhooks from Git so new commits sync in seconds. Remember the other side: during an incident, a human's emergency change will be reverted too, so GitOps teams make emergency changes through Git (fast-tracked PRs) or pause sync explicitly, and record it.
Try it yourself
- Add an
environments/stagingandenvironments/productionoverlay with Kustomize and a promotion step that copies an image tag between them by pull request. - Run two reconcilers against the same Deployment with different replica counts and watch them fight. How do field managers show it?
- Replace SOPS with Sealed Secrets or External Secrets and compare rotation workflows.
- On a cluster that can pull images, install Argo CD, point it at the same repository, and compare its UI's sync and health status with minigitops' log.
Revision sheet: GitOps
Key ideas
- Principles (OpenGitOps): declarative, versioned and immutable, pulled automatically, continuously reconciled.
- Push vs pull: credentials, drift, audit and rollback differences; CI builds and updates Git, agents deploy.
- Reconciliation: desired vs live state, diffing, server-side apply and field managers, pruning, health, sync waves and hooks, self-heal.
- Repository design: app repos vs config repos, environment overlays (Kustomize), Helm values, monorepo vs per-team, promotion by PR, image automation.
- Argo CD: Applications, ApplicationSets, projects, sync policies, UI, RBAC; Flux: GitRepository, Kustomization, HelmRelease, image automation, notification controller.
- Secrets: SOPS (age, KMS), Sealed Secrets, External Secrets Operator, CSI secrets store.
- Beyond apps: cluster add-ons, infrastructure via Crossplane or Terraform controllers, policies.
- Limits: databases and stateful migrations, emergency changes, secrets bootstrapping, ordering across systems.
Numbers to remember
- Lab: a commit reached all pods in ~4.7 s; a revert in ~4.6 s; drift lasted up to the sync interval (≤2 s at 3 s, ≤29.5 s at 30 s); a broken commit changed nothing; SOPS kept plaintext out of Git history.
Pitfalls
- Plain-text secrets in the repository.
- Pruning without ownership scoping.
- Mixing manual kubectl changes with GitOps (they're reverted).
- No CI validation of manifests before merge.
- One giant repo with everyone's permissions.
- Two controllers managing the same fields.
Glossary
- Reconciliation loop: continuously making actual state match desired state.
- Drift: live state differing from the declared state.
- Pruning: deleting live objects no longer declared.
- Field manager: the owner recorded by server-side apply for each field.
- Overlay: environment-specific changes on a shared base (Kustomize).
- Image automation: updating image tags in Git when new images are published.