TExcelTAD
Home › Kubernetes › GitOps

GitOps

With kubectl apply from laptops, nobody knows exactly what's running or who changed it. GitOps makes a Git repository the single source of truth for the cluster:

  1. Declarative: the desired state is described as manifests (plain YAML, Kustomize or Helm).
  2. Versioned: it lives in Git; every change is a commit, reviewed in a pull request.
  3. Pulled automatically: an agent inside the cluster pulls from Git; CI never needs cluster credentials.
  4. Continuously reconciled: the agent detects drift (someone ran kubectl edit) and reverts it.

The two popular agents are Argo CD and Flux, both CNCF graduated projects.

Argo CD

An Application tells Argo CD what to sync and where:

yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: shop-prod
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/acme/shop-deploy
    targetRevision: main
    path: overlays/production          # a Kustomize overlay
  destination:
    server: https://kubernetes.default.svc
    namespace: shop-prod
  syncPolicy:
    automated:
      prune: true                      # delete objects removed from Git
      selfHeal: true                   # revert manual changes
    syncOptions: [CreateNamespace=true]
bash
argocd app get shop-prod
argocd app diff shop-prod
argocd app sync shop-prod
argocd app history shop-prod

Sample output:

text
Name:               argocd/shop-prod
Sync Status:        OutOfSync from main (4e1c9a7)
Health Status:      Healthy

KIND        NAMESPACE  NAME       STATUS     HEALTH   HOOK  MESSAGE
Service     shop-prod  prod-api   Synced     Healthy        service/prod-api unchanged
Deployment  shop-prod  prod-api   OutOfSync  Healthy        deployment.apps/prod-api configured

Sync and drift, modelled

The agent compares three things: what Git says, what the cluster has, and what it applied last time (to know what to prune). This model computes the sync plan:

python · try it yourself
git = {
    "Deployment/api": {"image": "api:2.4.0", "replicas": 3},
    "Service/api": {"port": 80},
    "ConfigMap/api-config": {"LOG_LEVEL": "warn"},
}
cluster = {
    "Deployment/api": {"image": "api:2.4.0", "replicas": 5},   # someone ran kubectl scale
    "Service/api": {"port": 80},
    "CronJob/old-report": {"schedule": "0 2 * * *"},           # removed from Git last week
}
managed = {"Deployment/api", "Service/api", "CronJob/old-report"}   # applied by the agent before

def plan(git, cluster, prune=True):
    steps = []
    for key, want in git.items():
        have = cluster.get(key)
        if have is None:
            steps.append(f"create  {key}")
        elif have != want:
            diff = {k: f"{have.get(k)} -> {v}" for k, v in want.items() if have.get(k) != v}
            steps.append(f"patch   {key} {diff}")
    for key in sorted(cluster):
        if key not in git and key in managed:
            steps.append(f"{'delete ' if prune else 'orphan '} {key}")
    return steps or ["Synced"]

print("status:", "OutOfSync" if plan(git, cluster) != ["Synced"] else "Synced")
for step in plan(git, cluster):
    print("  " + step)
status: OutOfSync
  patch   Deployment/api {'replicas': '5 -> 3'}
  create  ConfigMap/api-config
  delete  CronJob/old-report

With selfHeal, the manual scale to 5 is reverted within minutes. If you need to change replicas, change Git (or let an HPA own replicas and tell the agent to ignore that field).

The promotion workflow

A typical setup keeps application code and deployment config in separate repositories:

text
app repo:     commit -> CI builds & tests -> pushes image ghcr.io/acme/api:2.4.1
deploy repo:  CI (or a bot) opens a PR: overlays/staging image tag 2.4.0 -> 2.4.1
              merge -> Argo CD syncs staging
              after checks, PR: overlays/production 2.4.0 -> 2.4.1 -> merge -> prod syncs
rollback:     git revert the promotion commit

The "bot" step can be as simple as editing the tag in the overlay's kustomization.yaml. A model:

python · try it yourself
import yaml

kustomization = yaml.safe_load("""
resources: [../../base]
images:
  - name: ghcr.io/acme/api
    newTag: "2.4.0"
  - name: ghcr.io/acme/worker
    newTag: "1.9.2"
""")

def bump(doc, image, tag):
    for entry in doc["images"]:
        if entry["name"] == image:
            old, entry["newTag"] = entry["newTag"], tag
            return f"chore(prod): bump {image.split('/')[-1]} {old} -> {tag}"
    raise KeyError(image)

message = bump(kustomization, "ghcr.io/acme/api", "2.4.1")
print("commit message:", message)
print(yaml.safe_dump(kustomization, sort_keys=False).strip())
commit message: chore(prod): bump api 2.4.0 -> 2.4.1
resources:
- ../../base
images:
- name: ghcr.io/acme/api
  newTag: 2.4.1
- name: ghcr.io/acme/worker
  newTag: 1.9.2

Secrets in GitOps

Git must never contain plain Secrets. Options:

  • Sealed Secrets: encrypt with the cluster's public key; only the in-cluster controller can decrypt.
  • SOPS (with age/KMS keys): encrypted values in YAML, decrypted by Flux or an Argo CD plugin.
  • External Secrets Operator: Git holds only a reference; values come from Vault, AWS Secrets Manager, etc.

Flux in one glance

Flux uses several small controllers and CRDs: a GitRepository (or OCIRepository) source plus Kustomization or HelmRelease objects that apply from it.

yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata: {name: shop-deploy, namespace: flux-system}
spec:
  url: https://github.com/acme/shop-deploy
  ref: {branch: main}
  interval: 1m
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata: {name: shop-prod, namespace: flux-system}
spec:
  sourceRef: {kind: GitRepository, name: shop-deploy}
  path: ./overlays/production
  prune: true
  interval: 5m

Test yourself

In GitOps, how does a change reach production?

  1. kubectl apply from a developer laptop
  2. A commit/merge to the Git repository, which the in-cluster agent syncs
  3. SSH into a node
  4. Editing etcd

What does Argo CD's selfHeal: true do?

  1. Restarts crashed Pods
  2. Reverts manual changes so the cluster matches Git again
  3. Backs up etcd
  4. Scales nodes

What is the simplest way to roll back a bad release in GitOps?

  1. kubectl delete namespace
  2. git revert the commit that promoted it
  3. Reboot the cluster
  4. Edit the Deployment by hand