GitOps: The Modern Way to Manage Infrastructure Using Git as the Single Source of Truth

3.96K 0 0 0 0

✅ Chapter 3: Managing Infrastructure and Applications Declaratively

🔍 Introduction

One of the foundational pillars of GitOps—and modern DevOps practices in general—is declarative management. Instead of manually scripting commands or modifying systems imperatively, you declare what you want the system to look like, and an automated engine ensures that reality matches your desired configuration.

In this chapter, you'll learn:

  • What "declarative management" really means
  • How to write and organize declarative infrastructure and application configurations
  • Key tools like Kustomize, Helm, and Terraform
  • Patterns for managing multiple environments
  • Real-world examples and workflows

Let’s explore how declarative thinking supercharges GitOps workflows.


🧠 What Does "Declarative Management" Mean?

In declarative management, you describe the desired state of your system, and a controller or automation tool ensures that the system converges to that state.

You don't tell the system how to reach the state — only what the state should be.


📋 Declarative vs Imperative Comparison

Aspect

Declarative

Imperative

Approach

Define the desired final state

Specify step-by-step commands

Focus

What the system should look like

How to achieve the desired state

Example

YAML manifest declaring 3 replicas

kubectl scale deployment myapp --replicas=3

Fault Tolerance

High (system ensures state)

Low (manual corrections needed)


🔥 Why Declarative is Better for GitOps

  • Consistency: Same Git state can recreate the system anytime.
  • Auditability: Git logs show what changed, not just what was executed.
  • Recovery: Easy disaster recovery from Git.
  • Automation: Controllers do the work, not humans.

🧱 Writing Declarative Infrastructure Configurations

Let's start with the basics: Infrastructure as Code (IaC).


🔹 Popular Declarative IaC Tools

Tool

Purpose

Terraform

Cloud infrastructure (AWS, GCP, Azure)

Pulumi

Cloud infra using programming languages

Crossplane

Kubernetes-native cloud management

AWS CDK

Infrastructure using code in languages like TypeScript, Python


📋 Sample Terraform for an AWS EC2 Instance

h

CopyEdit

resource "aws_instance" "web" {

  ami           = "ami-0c55b159cbfafe1f0"

  instance_type = "t2.micro"

 

  tags = {

    Name = "WebServer"

  }

}

This defines what infrastructure you want, not how to create it.

Apply it:

bash

CopyEdit

terraform apply

Terraform will calculate the steps needed and execute them.


🧰 Writing Declarative Application Configurations

Applications, especially containerized apps, are declared using Kubernetes manifests.


📄 Basic Kubernetes Deployment Manifest

yaml

CopyEdit

apiVersion: apps/v1

kind: Deployment

metadata:

  name: my-nginx

spec:

  replicas: 3

  selector:

    matchLabels:

      app: nginx

  template:

    metadata:

      labels:

        app: nginx

    spec:

      containers:

      - name: nginx

        image: nginx:1.25

        ports:

        - containerPort: 80

Kubernetes will create or update the system to match this declaration.


🛠️ Managing Configuration Complexity

When managing multiple apps and environments, raw YAML files quickly become messy. To avoid that:


🔹 1. Use Kustomize

  • Kustomize lets you layer configuration overrides without duplicating YAML.
  • Built into kubectl CLI.

Base:

yaml

CopyEdit

# deployment.yaml

apiVersion: apps/v1

kind: Deployment

metadata:

  name: app

spec:

  replicas: 1

  template:

    spec:

      containers:

      - name: app

        image: my-app:v1

Overlay for production:

yaml

CopyEdit

# overlays/prod/kustomization.yaml

bases:

- ../../base

patchesStrategicMerge:

- replica-patch.yaml

replica-patch.yaml:

yaml

CopyEdit

spec:

  replicas: 5

Command to apply:

bash

CopyEdit

kubectl apply -k overlays/prod/


🔹 2. Use Helm Charts

  • Helm is a package manager for Kubernetes.
  • Makes deployments dynamic using templated YAML.

Example:

yaml

CopyEdit

# values.yaml

replicaCount: 3

image:

  repository: nginx

  tag: 1.25

Install:

bash

CopyEdit

helm install my-release my-chart/

Helm makes upgrades, rollbacks, and parameterized deployments easy.


🔹 3. Split Configurations by Environment

Organize Git repos like this:

bash

CopyEdit

environments/

  dev/

    app-config.yaml

  staging/

    app-config.yaml

  prod/

    app-config.yaml

Environment-specific overlays allow tuning replicas, secrets, and resource limits separately.


🔐 Declarative Management of Secrets

Managing secrets declaratively is tricky but essential.


🔒 Popular Options

Tool

Approach

Sealed-Secrets

Encrypt Kubernetes Secrets for safe Git storage

SOPS + Git-crypt

Encrypt YAML files inside Git repo

External Secrets Operator

Fetch secrets from AWS Secrets Manager, Vault


Example: Sealed-Secret YAML

yaml

CopyEdit

apiVersion: bitnami.com/v1alpha1

kind: SealedSecret

metadata:

  name: db-password

spec:

  encryptedData:

    password: AgA3Jv0b5...

SealedSecret is safe to store and commit to Git!


📡 Applying Declarative GitOps Workflows

Bringing everything together:

  1. Declare all configs in Git (infra + apps).
  2. Push changes to the Git repository.
  3. GitOps agent (ArgoCD, Flux) detects and syncs.
  4. System applies state automatically.
  5. Drift detection corrects unauthorized changes.

🔥 Example: Full GitOps Folder Layout

bash

CopyEdit

gitops/

── apps/

│   ── base/

│   │   ── deployment.yaml

│   │   └── service.yaml

│   └── overlays/

│       ── dev/

│       ── staging/

│       └── prod/

── infrastructure/

│   ── vpc/

│   ── eks-cluster/

│   └── s3-buckets/

── secrets/

│   ── db-sealedsecret.yaml

│   └── api-keys-sealedsecret.yaml


📚 Declarative Management in Multi-Cluster, Multi-Cloud Environments

Organizations often need to manage:

  • Multiple Kubernetes clusters (e.g., dev, prod)
  • Multiple cloud providers (AWS, GCP, Azure)

With declarative configs:

  • You can sync different Git branches to different clusters.
  • Manage infrastructure cloud-agnostically using Terraform or Crossplane.
  • Set up multi-tenancy using ArgoCD projects or Flux's GitRepository objects.

🚀 Summary: What You Learned in Chapter 3


  • Declarative management defines desired state, not steps.
  • GitOps relies heavily on declarative configurations.
  • Tools like Terraform, Kustomize, Helm, and Sealed-Secrets simplify declarative workflows.
  • Managing environments declaratively leads to consistent, reproducible deployments.
  • Multi-cluster and multi-cloud operations are achievable through strong declarative practices.

Back

FAQs


❓1. What exactly is GitOps?

Answer: GitOps is a set of practices that use Git repositories as the single source of truth for managing infrastructure and application configurations. Changes are made by updating Git, and automated systems then synchronize the live system to match the Git repository.

❓2. How is GitOps different from traditional Infrastructure as Code (IaC)?

Answer: While both GitOps and IaC involve defining infrastructure using code, GitOps emphasizes automated synchronization, continuous reconciliation, and operations managed entirely through Git workflows—including deployments, rollbacks, and drift detection.

❓3. What tools are commonly used in a GitOps workflow?

Answer: Popular GitOps tools include:

  • ArgoCD (for Kubernetes GitOps)
  • Flux (another Kubernetes-native GitOps operator)
  • Terraform (for cloud infrastructure)
  • Helm and Kustomize (for Kubernetes resource templating)

❓4. Can GitOps be used outside Kubernetes?

Answer: Yes. While GitOps originated with Kubernetes, the principles can be applied to any system that supports declarative infrastructure (e.g., cloud resources using Terraform, databases, serverless deployments, and even networking configurations).

❓5. How does GitOps handle rollback or recovery?

Answer: Rollbacks in GitOps are simple—just revert the Git commit (or use Git history to reset configurations) and the GitOps controller will automatically reconcile the live environment back to that previous, stable state.

❓6. How does GitOps improve security?

Answer: GitOps enhances security by:

  • Reducing the need for direct access to production systems
  • Auditing every change through Git history
  • Enforcing peer reviews through pull requests
  • Allowing fine-grained RBAC at the Git repository level instead of cluster access

❓7. What are the main challenges of adopting GitOps?

Answer: Common challenges include:

  • Structuring Git repositories for scalability (mono-repo vs multi-repo)
  • Managing secrets securely within Git workflows
  • Handling merge conflicts in complex YAML or Terraform files
  • Building developer confidence with declarative and Git-centric operations

❓8. What happens if someone manually changes infrastructure without updating Git?

Answer: GitOps tools like ArgoCD or Flux continuously reconcile the live environment against the Git state. If drift is detected, they can either:

  • Alert you to manual changes
  • Automatically revert unauthorized changes back to the Git-defined state

❓9. Is GitOps only for large companies or microservices architectures?

Answer: No. GitOps can be beneficial for small startups, medium businesses, or large enterprises alike. Whether you're managing a handful of services or hundreds, GitOps provides automation, reliability, and clear operational visibility at all scales.

❓10. Can I implement GitOps gradually or do I need a full migration?

Answer: You can (and should) implement GitOps incrementally. Start with:

  • Non-critical services
  • Development environments
  • Kubernetes cluster resource management As your confidence and tooling mature, expand GitOps practices to production systems and more complex workloads.