# GitOps: Git says what runs, the cluster makes it so

Deploy by changing Git, not by pushing to servers: push versus pull, a Kustomize config repo, Argo CD and Flux syncing it to Kubernetes, drift repair, and git revert rollbacks.

Course: [CI/CD Pipelines](https://devops.rajeev.pro/courses/cicd), lesson 10. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/cicd/10-gitops

## What you will learn

- Explain push and pull deployment, and what GitOps changes about access and auditing
- Lay out a config repository with Kustomize, and change an image tag the way CI does
- Define an Argo CD Application that syncs, prunes and self-heals
- Define the same deployment in Flux with a GitRepository and a Kustomization
- Connect CI to GitOps: build the image, then commit its tag to the config repository
- Roll back with git revert, and see drift corrected automatically

## Push and pull deploys

In the deploys so far, CI **pushes**: it holds credentials for the target and runs commands against it. With
**GitOps**, nobody pushes to production. A Git repository describes what should run, and an agent inside the
cluster **pulls** it and makes the cluster match:

Push-based deployment gives the pipeline credentials for the cluster. If those credentials leak, an attacker can
change production directly. GitOps moves reconciliation into the cluster: an agent reads the approved desired
state from Git and applies the difference. In this lesson, you'll build a config repository, compare Argo CD and
Flux, and use a Git revert to roll back a release.

> **Figure.** Two deployment models. Push: CI builds the image and then connects to the cluster with kubectl and stored credentials to apply changes, so CI holds the keys to production. Pull, or GitOps: CI builds and pushes the image to a registry, then commits the new image tag to a config repository. Argo CD or Flux, running inside the cluster, watches that repository, notices the change and applies it. It also compares the cluster with Git continuously and repairs drift. A rollback is a git revert in the config repository. CI never touches the cluster.
>
> Push: CI reaches into production. Pull: CI changes Git, and the cluster updates itself.

|                                 | Push (CI applies)                      | Pull (GitOps)                                  |
| ------------------------------- | -------------------------------------- | ---------------------------------------------- |
| Who changes the cluster         | the pipeline, with cluster credentials | an agent inside the cluster                    |
| Credentials outside the cluster | yes, in CI secrets                     | none: CI only writes to Git                    |
| Audit trail                     | pipeline logs                          | Git history: who, what, when, approved by whom |
| Manual changes in the cluster   | stay until the next deploy             | undone automatically (self-heal)               |
| Rollback                        | re-run an old pipeline                 | `git revert`                                   |

The OpenGitOps principles sum it up: the desired state is **declarative**, **versioned** in Git, **pulled**
automatically, and **continuously reconciled**.

> **Video.** [GitOps CRASH COURSE For Beginners | ArgoCD & FluxCD | Vishakha Sadhwani](https://www.youtube.com/watch?v=xRIre6L_gAo&t=121s) (Vishakha Sadhwani)

## The config repository

GitOps needs a repository of manifests. A common layout keeps a shared **base** and one **overlay** per
environment, with **Kustomize** (built into `kubectl`):

```text
shop-config/
├── apps/shop-api/
│   ├── base/                  # what every environment shares
│   │   ├── deployment.yaml
│   │   ├── service.yaml
│   │   └── kustomization.yaml
│   └── production/
│       └── kustomization.yaml # production's namespace and image tag
└── clusters/production/
    └── argocd-shop-api.yaml   # tells Argo CD what to sync
```

The base is an ordinary Deployment and Service:

```yaml
# apps/shop-api/base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-api
spec:
  replicas: 2
  selector:
    matchLabels: { app: shop-api }
  template:
    metadata:
      labels: { app: shop-api }
    spec:
      containers:
        - name: shop-api
          image: ghcr.io/elonerajeev/shop-api:1.0.0
          ports:
            - containerPort: 3000
          readinessProbe:
            httpGet: { path: /health, port: 3000 }
          resources:
            requests: { cpu: 50m, memory: 64Mi }
            limits: { memory: 128Mi }
```

```yaml
# apps/shop-api/base/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: shop-api
spec:
  selector: { app: shop-api }
  ports:
    - port: 80
      targetPort: 3000
```

```yaml
# apps/shop-api/base/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources: [deployment.yaml, service.yaml]
```

The production overlay reuses the base and sets what's specific to production:

```yaml
# apps/shop-api/production/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop
resources: [../base]
images:
  - name: ghcr.io/elonerajeev/shop-api
    newTag: 1.0.0
```

A release is one line changing. CI does it with Kustomize:

```sh
$ cd apps/shop-api/production
$ kustomize edit set image ghcr.io/elonerajeev/shop-api:1.0.43-9f2a1bc
$ grep -A2 '^images' kustomization.yaml
images:
- name: ghcr.io/elonerajeev/shop-api
  newTag: 1.0.43-9f2a1bc
$ kustomize build . | kubeconform -strict -summary -
Summary: 2 resources found parsing stdin - Valid: 2, Invalid: 0, Errors: 0, Skipped: 0
```

`kustomize build` renders the final manifests, and **kubeconform** validates them against the Kubernetes
schemas, so a typo fails in CI instead of in the cluster.

The base holds settings shared by environments; an overlay changes only what differs, such as the image tag or
replica count. Rendering an overlay shows the exact manifest the reconciler will apply. Validate that rendered
output, not just the source snippets, because patches can combine in unexpected ways. Keep environment overlays
reviewed separately and do not put plaintext credentials in the config repository.

## Argo CD

> **Figure.** Animated. CI commits a new image tag, 1.0.43, to the config repository. Argo CD, inside the cluster, notices the cluster no longer matches Git (OutOfSync), syncs, and the pods change to 1.0.43 (Synced). Then someone scales the deployment by hand to 5 replicas. Argo CD detects the drift from Git, which says 2, and self-heal scales it back to 2.
>
> A commit changes the tag and Argo CD rolls it out. A manual kubectl change is drift, and self-heal undoes it.

**Argo CD** runs in the cluster and syncs **Applications**: each one points at a path in a Git repository
and a destination in the cluster. It has a web UI showing every resource, its health and its diff from Git.

```yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: shop-api
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/elonerajeev/shop-config.git
    targetRevision: main
    path: apps/shop-api/production
  destination:
    server: https://kubernetes.default.svc     # the cluster Argo CD runs in
    namespace: shop
  syncPolicy:
    automated:
      prune: true           # delete what was removed from Git
      selfHeal: true        # undo manual changes in the cluster
    syncOptions:
      - CreateNamespace=true
```

| Setting     | Without it                                                    |
| ----------- | ------------------------------------------------------------- |
| `automated` | Argo CD shows _OutOfSync_ and waits for someone to click Sync |
| `prune`     | a manifest deleted from Git leaves its resource running       |
| `selfHeal`  | a `kubectl edit` in production stays until the next commit    |

The first `Application` is applied once with `kubectl apply -f`; after that, Argo CD can manage its own
Applications from Git too (the "app of apps" pattern).

## Flux

**Flux** does the same job as a set of small controllers with no central UI, configured entirely with
Kubernetes resources: a **source** to watch, and what to apply from it:

```yaml
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: shop-config
  namespace: flux-system
spec:
  interval: 1m                # check Git every minute
  url: https://github.com/elonerajeev/shop-config
  ref:
    branch: main
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: shop-api
  namespace: flux-system
spec:
  interval: 5m                # re-apply and repair drift every 5 minutes
  sourceRef:
    kind: GitRepository
    name: shop-config
  path: ./apps/shop-api/production
  prune: true
  targetNamespace: shop
  wait: true                  # healthy only when the rollout finishes
  timeout: 2m
```

|               | Argo CD                                       | Flux                                               |
| ------------- | --------------------------------------------- | -------------------------------------------------- |
| Shape         | one app with a rich web UI                    | small controllers, CLI-first                       |
| Unit          | `Application` (and `ApplicationSet` for many) | `GitRepository` + `Kustomization` or `HelmRelease` |
| Multi-cluster | one Argo CD can manage many clusters          | usually Flux in each cluster                       |
| Extras        | UI, SSO, sync waves, rollouts                 | image automation that commits new tags for you     |

Both are CNCF graduated projects. Pick Argo CD when people want to see and click; pick Flux when everything,
including Flux itself, should be plain YAML in Git. Both manifests above pass kubeconform with the CRD schemas
from the community catalog, and a typo such as `selfHeel` is reported as
`additional properties 'selfHeel' not allowed`.

Argo CD and Flux both reconcile Git into cluster state, but their operating interfaces differ. Argo CD centers
applications and provides a web view for sync and drift. Flux uses smaller controllers and Kubernetes resources,
and is commonly operated through Git and its CLI. Neither tool makes a weak repository policy safe. Choose the
one your team can monitor and upgrade, and assign an owner for failed syncs and pending changes.

## CI and GitOps together

CI still builds, tests and publishes the image (lessons 5 and 6). Its last job is just a commit:

```yaml
update-config:
  runs-on: ubuntu-latest
  environment: production                 # approval before production (lesson 4)
  steps:
    - uses: actions/checkout@v7
      with:
        repository: elonerajeev/shop-config
        token: ${{ secrets.CONFIG_REPO_TOKEN }}   # can write to the config repo only
    - name: Set the new image tag
      working-directory: apps/shop-api/production
      env:
        VERSION: ${{ inputs.version }}
      run: |
        [[ $VERSION =~ ^[0-9]+\.[0-9]+\.[0-9]+-[0-9a-f]{7}$ ]] || { echo "bad version: $VERSION"; exit 1; }
        kustomize edit set image "ghcr.io/elonerajeev/shop-api:$VERSION"
    - name: Commit and push
      env:
        VERSION: ${{ inputs.version }}
      run: |
        git config user.name "shop-api release bot"
        git config user.email "shop-api-bot@users.noreply.github.com"
        git commit -am "shop-api: deploy $VERSION to production"
        git push
```

The version check refuses anything that isn't a real tag: `x; echo pwned` and `1.0.43` are both rejected.
The token can write to one repository and nothing else; the cluster's credentials never leave the cluster.

CI still owns building and testing the image. GitOps changes the final handoff: CI writes a reviewed image
reference to the config repository, and the in-cluster agent performs the deployment. Validate the tag before
writing it so untrusted text cannot become shell syntax. Give the release token access only to that repository,
and use a pull request when the change needs human approval. This separates build permissions from cluster
permissions while preserving an audit trail for desired state.

### Rolling back

```sh
$ git log --oneline -2
f49d2b7 shop-api: deploy 1.0.43-9f2a1bc to production
b2d9f32 shop-api: deploy 1.0.42-e3b0c44 to production
$ git revert --no-edit f49d2b7 && git push     # Argo CD or Flux rolls 1.0.42 back out
```

> **In production.** Protect the config repository like production itself: required reviews, CODEOWNERS per environment, and no direct pushes except from the release bot. Never commit plain secrets to it; use Sealed Secrets, SOPS or the External Secrets Operator so Git holds only encrypted values or references. And alert on *OutOfSync* or failed syncs, so a broken commit doesn't sit unnoticed.

## Mission: Build shop-api's config repository

Create the shop-config repository with a base and a production overlay for shop-api, an Argo CD Application and the Flux equivalent. Validate everything with kustomize and kubeconform, change the image tag the way CI would, and practise a rollback with git revert.

- You need: kustomize and kubeconform (single binaries), Git
- You'll have: A config repository whose every commit renders and validates

```sh
$ mkdir -p shop-config/apps/shop-api/{base,production} shop-config/clusters/production && cd shop-config && git init
$ nano apps/shop-api/base/deployment.yaml apps/shop-api/base/service.yaml apps/shop-api/base/kustomization.yaml
$ nano apps/shop-api/production/kustomization.yaml
$ nano clusters/production/argocd-shop-api.yaml clusters/production/flux-shop-api.yaml
$ kustomize build apps/shop-api/production | kubeconform -strict -summary -
Summary: 2 resources found parsing stdin - Valid: 2, Invalid: 0, Errors: 0, Skipped: 0
$ kubeconform -strict -summary -schema-location default \
    -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
    clusters/production/
Summary: 3 resources found in 2 files - Valid: 3, Invalid: 0, Errors: 0, Skipped: 0
$ git add . && git commit -m "shop-api: production at 1.0.0"
$ (cd apps/shop-api/production && kustomize edit set image ghcr.io/elonerajeev/shop-api:1.0.43-9f2a1bc)
$ git commit -am "shop-api: deploy 1.0.43-9f2a1bc to production"
$ git revert --no-edit HEAD && grep newTag apps/shop-api/production/kustomization.yaml
  newTag: 1.0.0
```

The 3 resources are the Argo CD Application plus Flux's GitRepository and Kustomization (in practice you'd
run one of the two tools; both are here to compare). Every file is in this lesson. With a local cluster (kind), install Argo CD from its getting-started guide and apply
`clusters/production/argocd-shop-api.yaml` to see it sync.

## Try it

- Write a base Kustomization and a production overlay, and render it with `kustomize build`.
- Change the image tag with `kustomize edit set image` and read the diff it makes.
- Install Argo CD on a local cluster (kind or minikube) and apply the Application from this lesson.
- Run `kubectl scale deployment shop-api --replicas=5` and watch Argo CD put it back to 2.
- Revert the last commit in the config repository and watch the old version roll out.
- Validate the manifests with kubeconform before committing them.

## Quiz

1. What is the main difference between push and pull deployment?
   - Speed
   - **In push, CI connects to the cluster and applies changes; in pull, an agent in the cluster watches Git and applies them itself** (answer)
   - Pull is only for Docker
   - There is none
   Why: With pull, CI never holds cluster credentials. Git becomes the only way to change production, and its history is the audit log.

2. Someone changes a Deployment in the cluster by hand. What does Argo CD with selfHeal true do?
   - Nothing
   - **Detects the drift from Git and changes it back to what Git says** (answer)
   - Commits the change to Git
   - Deletes the Deployment
   Why: The cluster converges to Git. Changes that matter go through a pull request; manual fixes are undone.

3. How do you roll back a bad release in GitOps?
   - kubectl rollout undo in production
   - **git revert the commit that changed the image tag in the config repository** (answer)
   - Delete the namespace
   - Rebuild the old image
   Why: The revert is reviewed, recorded and synced like any change. A kubectl rollback would be overwritten at the next sync.

4. Why keep Kubernetes config in a separate repository from the app code?
   - Git can't hold YAML
   - **Deploy changes get their own history, reviewers and access rules, and CI committing a tag doesn't retrigger app builds** (answer)
   - Argo CD requires it
   - It's faster
   Why: Many teams do keep both in one repository; separating them is the common default once several services and environments exist.

5. What does prune true do in an Argo CD or Flux sync?
   - Deletes old Git branches
   - **Deletes resources from the cluster that were removed from Git** (answer)
   - Compresses images
   - Removes logs
   Why: Without prune, deleting a manifest from Git leaves the resource running forever.

## Resources

- [OpenGitOps principles](https://opengitops.dev/) (OpenGitOps (CNCF))
- [Argo CD: getting started](https://argo-cd.readthedocs.io/en/stable/getting_started/) (Argo CD)
- [Argo CD: automated sync policy](https://argo-cd.readthedocs.io/en/stable/user-guide/auto_sync/) (Argo CD)
- [Flux: get started](https://fluxcd.io/flux/get-started/) (Flux)
- [Kustomize documentation](https://kubectl.docs.kubernetes.io/references/kustomize/) (Kubernetes)
- [kubeconform: Kubernetes manifest validator](https://github.com/yannh/kubeconform) (kubeconform)
