DevopsIntermediate

GitOps: Infrastructure as Code with Git-Centric Workflows

DeveloperHat Team
9 min read

TL;DR

Learn how to implement GitOps practices for infrastructure management, continuous deployment, and automated operations using tools like ArgoCD and Flux

Executive Summary

GitOps makes a Git repository the single source of truth for the desired state of a system, and puts an automated agent in charge of making the real system match it. This guide covers the operating model end to end: the principles (declarative configuration, versioned state, pull-based reconciliation, drift correction), a concrete implementation with Argo CD and Kustomize, the CI pipeline that feeds it by updating image tags in Git, and the repository structure and security controls that keep it trustworthy. After reading it, you will be able to set up a working GitOps loop for a Kubernetes service and decide how far to extend it across environments and infrastructure.

The GitOps loop: Git is the source of truth, the agent closes the gap Commit to Git desired state, reviewed CI tests + builds image published Image tag in Git config repo updated Agent pulls state Argo CD / Flux Cluster reconciled live matches Git Drift corrected self-heal + alert Rollback is a revert, not a redeploy — every state corresponds to a commit.

Why This Matters

In a conventional pipeline, deployment is an event: a job runs, applies changes, and exits. Afterwards, nothing guarantees the cluster still matches what was deployed — an engineer with kubectl access can hotfix production at 2 a.m., and that fix exists nowhere in version control. The next deployment silently reverts it, or worse, nobody knows it happened. GitOps inverts this. Because an agent continuously reconciles live state against Git, unauthorised or accidental changes are detected and corrected, every production state corresponds to a commit, and rollback is a revert rather than a redeploy. The audit trail stops being a separate compliance artefact and becomes a by-product of how deployment works. For teams answering to regulators, that property alone can justify the model; for everyone else, the operational calm of "the cluster is what Git says it is" does.

Core Concepts

The Principles

GitOps rests on a small set of commitments. The entire system is described declaratively — manifests state what should exist, not steps to produce it. That description is versioned in Git, which becomes the single source of truth and the complete history of every change. An agent pulls the desired state from Git and applies it, rather than a CI system pushing into the cluster with powerful credentials. And reconciliation is continuous: the agent keeps comparing desired and actual state, reporting drift and, where configured, correcting it automatically. If any one of these is missing — especially the pull model and continuous reconciliation — you have ordinary CI/CD with extra repositories.

Structuring Configuration with Kustomize

Environment differences are the hard part of declarative configuration. Kustomize handles them with a base set of manifests plus per-environment overlays that patch the differences: image tags, replica counts, configuration values.

# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - deployment.yaml
  - service.yaml
  - ingress.yaml
  - configmap.yaml
  - secret.yaml

namePrefix: myapp-
nameSuffix: -prod

commonLabels:
  app: myapp
  environment: production

commonAnnotations:
  maintainer: devops-team
  contact: devops@example.com

configMapGenerator:
  - name: app-config
    files:
      - config/app.properties
    literals:
      - API_URL=https://api.example.com
      - ENVIRONMENT=production

secretGenerator:
  - name: app-secrets
    files:
      - secrets/api-key.txt
    literals:
      - DB_PASSWORD=ENC[AES256_GCM,data:xxx,tag:yyy]

images:
  - name: myapp
    newName: registry.example.com/myapp
    newTag: v1.2.3

patches:
  - path: patches/increase-replica-count.yaml
    target:
      kind: Deployment
      name: myapp

replacements:
  - source:
      kind: ConfigMap
      name: app-config
      fieldPath: data.API_URL
    targets:
      - select:
          kind: Deployment
          name: myapp
        fieldPaths:
          - spec.template.spec.containers.[name=myapp].env.[name=API_URL].value

configurations:
  - kustomizeconfig.yaml

Helm charts fill the same role for packaged applications; many estates use both — Helm for third-party software, Kustomize overlays for their own services. Keep environment differences visible in the overlay rather than burying them in templating logic, because the overlay diff is what a reviewer actually approves.

The Reconciliation Agent: Argo CD

Argo CD is the most widely adopted agent. An Application resource binds a Git path to a destination cluster and namespace, and the sync policy decides how aggressively Argo CD enforces it:

# application.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: myapp
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/your-org/your-repo.git
    targetRevision: HEAD
    path: k8s/overlays/production
    kustomize:
      images:
        - registry.example.com/myapp:v1.2.3
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true
      - PruneLast=true
      - ApplyOutOfSyncOnly=true
    retry:
      limit: 5
      backoff:
        duration: 5s
        factor: 2
        maxDuration: 3m
  ignoreDifferences:
    - group: apps
      kind: Deployment
      jsonPointers:
        - /spec/replicas
  revisionHistoryLimit: 10

Read the policy fields carefully, because they are operational decisions. prune deletes resources removed from Git — powerful, and dangerous if a repository is restructured carelessly. selfHeal reverts manual changes to managed fields. ignoreDifferences is the escape hatch for fields legitimately owned by something else, such as a replica count managed by an autoscaler. Flux CD implements the same model as a set of native Kubernetes controllers; the concepts transfer directly.

The GitOps stack — the agent, not the pipeline, touches the cluster Git — versioned desired state, PR review, audit trail CI — build, test, publish image, update the tag in Git Agent — Argo CD / Flux pulls and syncs, prune + self-heal Cluster — live state, namespaces, workloads, overlays Observability — drift alerts, sync status, who changed what CI never touches the cluster — its job ends at recording the image in Git.

CI Feeds Git, Git Feeds the Cluster

In GitOps, CI never touches the cluster. Its job ends at publishing an image and recording that fact in the configuration repository, which the agent then picks up:

  update-manifests:
    needs: build-image
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Install Kustomize
        run: |
          curl -s "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh" | bash
          sudo mv kustomize /usr/local/bin/
      
      - name: Update image tag
        run: |
          cd k8s/overlays/production
          kustomize edit set image ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
      
      - name: Commit and push changes
        run: |
          git config --global user.name 'GitHub Actions'
          git config --global user.email 'actions@github.com'
          git add k8s/overlays/production/kustomization.yaml
          git commit -m "Update image tag to ${{ github.sha }}"
          git push

This separation is also a security improvement: CI needs only registry and Git credentials, while the powerful cluster credentials live inside the cluster with the agent. Promotion between environments becomes a pull request against the configuration repository — reviewable, approvable, and reversible with the same tooling as code changes.

Repository Structure and Security

Two layouts dominate: a single configuration repository for all environments, or one repository per environment or tenant. Single-repo is simpler and gives atomic cross-environment visibility; separate repositories give stronger access control, at the cost of more moving parts. Application source code usually lives apart from deployment configuration, so that a manifest change does not trigger an application build and vice versa. Security follows from the model: protect the configuration repository like production itself (branch protection, required reviews), because write access to it is deploy access. Secrets never enter Git in plaintext — use an external secrets integration, sealed secrets, or encrypted files with a tool such as SOPS. Scope the agent's Kubernetes permissions per namespace or project, and monitor its sync status and health as production signals in their own right.

Should this workload be GitOps? Decide by blast radius, not by fashion How many clusters? and who can change them Many / regulated audit trail required One, small team a few services Prototype / no cluster still finding shape Full GitOps Argo CD + PR review GitOps-lite Flux + Kustomize Plain CI/CD push revisit when it grows If nothing reconciles drift, you have CI/CD with extra repositories.

Decision Framework

SituationRecommendation
Single team, few services, one clusterArgo CD or Flux with one configuration repo; automated sync with prune and self-heal
Multiple environments with formal promotionSeparate overlays per environment; promotion by pull request between them
Regulated or audited environmentManual approval on the production configuration repo; self-heal on, every change a reviewed commit
Many teams sharing clustersPer-team repositories or Argo CD projects with scoped destinations and RBAC
Autoscaled workloadsConfigure ignoreDifferences for controller-owned fields such as replicas
Non-Kubernetes infrastructureApply the same principles with Terraform and a plan/apply pipeline; do not force a Kubernetes controller onto it
Very small or short-lived projectSkip GitOps; a CI deploy job is proportionate

Implementation Checklist

  • [ ] Desired state for the service is fully declared in Git — nothing is applied by hand
  • [ ] The agent reconciles automatically, with prune and self-heal settings chosen deliberately per environment
  • [ ] CI publishes images and updates configuration in Git; CI holds no cluster credentials
  • [ ] The configuration repository has branch protection and required review for production paths
  • [ ] Secrets are externalised or encrypted; a scan confirms no plaintext credentials in history
  • [ ] Agent permissions are scoped to the namespaces it manages
  • [ ] Sync status and application health alert into the normal incident channel
  • [ ] Rollback by Git revert has been performed at least once in a non-production environment
  • [ ] A break-glass procedure exists for when Git or the agent is unavailable, and its use is audited
  • Trade-offs

    GitOps adds a reconciliation delay: a merged change lands when the agent next syncs, not instantly, and debugging a failed deployment means reading the agent's state as well as the application's. Git becomes critical production infrastructure — an outage or a bad merge to the configuration repository affects every environment that trusts it. The model also assumes your workloads can be fully described declaratively; stateful systems, one-off data migrations, and imperative operational tasks fit awkwardly and need explicit exceptions. Finally, drift correction is a double-edged property: self-heal will faithfully revert a legitimate emergency hotfix applied directly to the cluster, so the break-glass path must feed changes back into Git quickly, or the agent becomes an adversary during incidents.

    When Not to Use

    Do not adopt GitOps for a single small application where a CI deploy job already works — the agent, repositories, and policy machinery cost more than the drift problem they solve. Do not adopt it as a first step into Kubernetes; a team still learning basic workload management will struggle to distinguish platform problems from GitOps problems. And do not force stateful data operations — schema migrations with ordering constraints, manual data repairs — through a declarative sync loop; run those as controlled jobs with human oversight, and let GitOps manage the stateless surface it is good at.

    Conclusion

    GitOps earns its place by making production state a function of a reviewed, versioned repository: drift is corrected, rollbacks are reverts, and the audit trail writes itself. Implement it with a clear repository structure, a deliberately configured sync policy, and secrets kept out of Git. Start with one service and one environment, prove the loop including a rollback, then extend it.

    References

  • ArgoCD Documentation
  • Flux Documentation
  • GitOps Principles
  • Kubernetes Best Practices
  • Container Security
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.