# GitOps Basics and Workflows

> **CNPA Domain:** Platform Engineering Core Fundamentals (36%) · Continuous Delivery & Platform Engineering (16%) **Topics:** Continuous Delivery and GitOps, GitOps Basics and Workflows

## Overview

**GitOps** is an operational model where the entire desired state of a system — applications, infrastructure, configuration — is declared in a Git repository and continuously reconciled by automated agents. Git becomes the single source of truth, making all changes auditable, reversible, and reliable.

For platform engineers, GitOps is not just a deployment strategy — it's the foundation for managing multiple environments, tenant clusters, and platform capabilities at scale.

***

## The Four GitOps Principles (OpenGitOps)

The [OpenGitOps](https://opengitops.dev/) project defines four core principles:

| # | Principle                   | Meaning                                             |
| - | --------------------------- | --------------------------------------------------- |
| 1 | **Declarative**             | Desired system state is expressed declaratively     |
| 2 | **Versioned and Immutable** | State is stored in Git with full history            |
| 3 | **Pulled Automatically**    | Agents automatically pull and apply changes         |
| 4 | **Continuously Reconciled** | Agents continuously compare desired vs actual state |

***

## Push vs Pull Deployment Models

### Traditional Push Model (CI-based)

```
CI Pipeline
    → kubectl apply (push)
    → Cluster
```

Problems:

* CI system needs cluster credentials (security risk)
* No continuous reconciliation — drift goes undetected
* Hard to audit who changed what, when

### GitOps Pull Model

```
Developer pushes to Git
    ↓
Git Repository (source of truth)
    ↓
GitOps Agent (running IN the cluster)
    ↓ polls / watches Git
Cluster continuously reconciled to Git state
```

Benefits:

* Cluster credentials never leave the cluster
* Drift is automatically detected and corrected
* Full audit trail in Git history
* Rollback = `git revert`

***

## GitOps Workflow

```
Developer
  │  git push (feature branch)
  ↓
Pull Request
  │  peer review + CI checks
  ↓
Merge to main
  │
Git Repository (manifests/Helm values updated)
  │
GitOps Controller (ArgoCD / Flux) detects change
  │  reconcile loop: desired state ≠ actual state
  ↓
Kubernetes Cluster (actual state updated)
  │
Deployment complete → notification
```

***

## Argo CD

[Argo CD](https://argo-cd.readthedocs.io/) is the most widely adopted GitOps continuous delivery tool for Kubernetes.

### Core Concepts

| Concept         | Description                                                 |
| --------------- | ----------------------------------------------------------- |
| **Application** | An ArgoCD CRD linking a Git source to a cluster destination |
| **Project**     | Grouping of Applications with RBAC policies                 |
| **Sync**        | The action of applying Git state to the cluster             |
| **Health**      | Whether Kubernetes resources are functioning correctly      |

### Example ArgoCD Application

```yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: payment-service
  namespace: argocd
spec:
  project: payments-team

  source:
    repoURL: https://github.com/example/platform-gitops
    targetRevision: HEAD
    path: apps/payment-service/overlays/production

  destination:
    server: https://kubernetes.default.svc
    namespace: payments-production

  syncPolicy:
    automated:
      prune: true        # Delete removed resources
      selfHeal: true     # Correct manual changes
    syncOptions:
      - CreateNamespace=true
```

### ArgoCD Sync + Health Status

```
Out of Sync  →  Syncing  →  Synced
                               ↓
                         Progressing  →  Healthy
                                     →  Degraded
```

***

## Flux CD

[Flux](https://fluxcd.io/) is a CNCF graduated GitOps toolkit with a modular, Kubernetes-native controller architecture.

### Flux Components

| Controller                      | Purpose                                  |
| ------------------------------- | ---------------------------------------- |
| **source-controller**           | Monitors Git repos, Helm repos, OCI      |
| **kustomize-controller**        | Applies Kustomize resources from sources |
| **helm-controller**             | Manages HelmRelease objects              |
| **notification-controller**     | Sends alerts and receives webhooks       |
| **image-reflector-controller**  | Monitors container registries            |
| **image-automation-controller** | Auto-updates image tags in Git           |

```yaml
# Flux: GitRepository source
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: platform-gitops
  namespace: flux-system
spec:
  interval: 1m
  url: https://github.com/example/platform-gitops
  ref:
    branch: main
---
# Flux: Kustomization (apply workloads)
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: payment-service
  namespace: flux-system
spec:
  interval: 5m
  sourceRef:
    kind: GitRepository
    name: platform-gitops
  path: ./apps/payment-service/production
  prune: true
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: payment-service
      namespace: payments-production
```

***

## Repository Structure Patterns

### Monorepo (App + Config in one repo)

```
my-service/
├── src/               # Application code
├── Dockerfile
├── .github/workflows/ # CI pipeline
└── k8s/
    ├── base/
    └── overlays/
        ├── staging/
        └── production/
```

Best for: small teams, simple services.

### Split Repos (App repo + GitOps repo)

```
my-service/            ← Application code + CI
  → CI produces image, updates gitops-repo

platform-gitops/       ← All environment manifests
  apps/
    payment-service/
      staging/
      production/
  infrastructure/
    monitoring/
    networking/
```

Best for: platform teams managing many services, multi-team environments.

Platform teams typically maintain a **central GitOps repository** and give teams self-service access to submit changes via PRs.

***

## Reconciliation and Drift Detection

GitOps agents continuously run a **reconciliation loop**:

```
Every N minutes / on Git change:
  1. Fetch desired state from Git
  2. Fetch actual state from cluster API
  3. Diff desired vs actual
  4. If diff exists:
       - Apply changes (selfHeal=true)
       - OR alert/block (selfHeal=false)
```

This means manual `kubectl` changes are automatically reverted if `selfHeal` is enabled — ensuring Git is always the source of truth.

***

## GitOps vs Traditional CI/CD

| Aspect             | Traditional CI/CD             | GitOps                       |
| ------------------ | ----------------------------- | ---------------------------- |
| Deployment trigger | CI pipeline push              | Git commit + pull by agent   |
| Credentials        | CI server holds cluster creds | Agent inside cluster only    |
| Rollback           | Re-run pipeline               | `git revert`                 |
| Drift detection    | Manual/none                   | Automatic, continuous        |
| Audit trail        | CI logs                       | Git history                  |
| Multi-cluster      | Complex                       | Natural (per-cluster agents) |

***

## Key Takeaways

* GitOps makes Git the **single source of truth** for desired system state
* The **pull model** is more secure than push: cluster credentials never leave the cluster
* **ArgoCD** and **Flux** are the dominant CNCF-ecosystem GitOps controllers
* **Reconciliation loops** continuously detect and correct drift
* Use a **split repo pattern** (app repo + GitOps repo) for multi-team, multi-environment platforms
* GitOps makes rollback trivial: revert the commit

***

## Further Reading

* [OpenGitOps Principles](https://opengitops.dev/)
* [Argo CD Documentation](https://argo-cd.readthedocs.io/)
* [Flux Documentation](https://fluxcd.io/docs/)
* [CNCF GitOps Working Group](https://github.com/cncf/tag-app-delivery/tree/main/gitops-wg)
* → Next: [GitOps for Application Environments](https://blog.htunnthuthu.com/getting-started/fundamentals/platform-engineering-101/platform-engineering-101-gitops-app-environments)
