Learn Kubernetes Β· 14/14

GitOps and Continuous Deployment

9 min read

Course: Kubernetes

Topic: GitOps and Continuous Deployment

Welcome, fellow container orchestrators! Orchestrating containers can sometimes feel like trying to conduct a symphony of cats. 🐈 Each one has its own idea of where to go and what to do. This is where GitOps comes in, bringing a Zen-like calm to the beautiful chaos of Kubernetes deployments.

In this guide, we'll explore the world of GitOps and how it revolutionizes continuous deployment in a Kubernetes environment. Ready to make your deployments smoother than a fresh jar of peanut butter? Let's dive in!


1. The GitOps Philosophy: Git as the Single Source of Truth πŸ“œ

The Problem: The "It Worked on My Machine" Nightmare

Imagine this: a developer, let's call him Dave, pushes some new code. It works perfectly on his local machine. The operations team then tries to deploy it to production, and... it breaks. πŸ’₯ Finger-pointing ensues. Dave says the Ops team configured the environment incorrectly. The Ops team says Dave's code is buggy. This, my friends, is what we call "configuration drift," where the state of your application in different environments is inconsistent.

Another spooky story is the "mystery change." Someone, somewhere, made a manual change to the production environment to fix a small issue. Now, a week later, a new deployment fails because of this undocumented change. Nobody knows who did it, why they did it, or how to undo it. It's like a ghost in the machine, but less fun.

The core problem is the lack of a single, reliable source of truth for the desired state of your application and its environment.

The Solution: GitOps to the Rescue!

GitOps is an operational framework that takes DevOps best practices used for application development and applies them to infrastructure automation.

At its heart, GitOps declares that a Git repository is the single source of truth for your entire system. This means that not just your application code, but also the configuration of your Kubernetes clusters, deployments, services, and everything in between, lives in a Git repository.

If you want to make a change to your infrastructure, you don't SSH into a server and start typing commands. Instead, you make a pull request to the Git repository. Once that pull request is reviewed and merged, an automated process takes over to apply those changes to your live environment.

Think of your Git repository as the ultimate instruction manual for your infrastructure. If it's not in Git, it doesn't exist in your cluster. This simple yet powerful idea has some amazing benefits:

  • Auditability: Every single change to your system is a commit in Git. You have a perfect audit trail of who changed what, when, and why. No more mystery changes!
  • Consistency and Reproducibility: Because everything is defined in Git, you can easily recreate your entire environment from scratch. This is a lifesaver for disaster recovery.
  • Developer-Centric Experience: Developers can use the same familiar Git workflow they use for application code to manage infrastructure. This empowers them to take more ownership of their applications in production.
  • Enhanced Security: By enforcing changes through pull requests, you can implement review and approval processes, ensuring that no unauthorized changes make it to production.

This philosophy transforms your infrastructure management from a manual, error-prone process into a declarative, automated, and auditable one.


2. Integrating Kubernetes into Traditional CI/CD Pipelines πŸ”„

So, you're sold on the idea of GitOps, but you already have a CI/CD pipeline. Don't worry, you don't have to throw it all away! GitOps complements and enhances traditional CI/CD.

The Old Way vs. The GitOps Way

In a traditional CI/CD pipeline (often called "push-based"), the process typically looks like this:

  1. A developer pushes code to a Git repository.
  2. The CI (Continuous Integration) server (like Jenkins, GitLab CI, or GitHub Actions) runs tests and builds a container image.
  3. The CD (Continuous Deployment) part of the pipeline then pushes this new image and any configuration changes directly to the Kubernetes cluster using kubectl commands.

This works, but it has some drawbacks:

  • The CI/CD tool needs direct access to the Kubernetes cluster. This can be a security risk.
  • It's harder to roll back. If a deployment fails, you have to trigger the pipeline again with the old version.
  • It doesn't prevent configuration drift. Someone could still make manual changes to the cluster that the CI/CD pipeline doesn't know about.

In a GitOps pipeline (a "pull-based" approach), the flow is a bit different and a lot more elegant:

  1. A developer pushes application code to the application repository.
  2. The CI pipeline runs tests, builds a container image, and pushes it to a container registry.
  3. Here's the key difference: Instead of deploying to Kubernetes, the CI pipeline updates a YAML file in a separate configuration repository with the new image tag.
  4. An agent running in the Kubernetes cluster (we'll talk about ArgoCD soon!) constantly watches the configuration repository.
  5. When the agent detects a change (the new image tag), it pulls the updated configuration and applies it to the cluster.

This pull-based model is the secret sauce of GitOps. The cluster itself is responsible for keeping its state in sync with the Git repository.


3. Introduction to ArgoCD: Declarative Continuous Delivery β›΅

Now, let's meet the friendly octopus that makes this pull-based magic happen: ArgoCD.

ArgoCD is a declarative, GitOps continuous delivery tool for Kubernetes. It's one of the most popular and widely used tools in the GitOps space, and for good reason!

In simple terms, ArgoCD's job is to continuously monitor a Git repository and a running Kubernetes cluster and make sure they are in sync. If the live state of the cluster drifts from the state defined in Git, ArgoCD will notice and can automatically correct it.

Getting Started with ArgoCD

Let's get our hands dirty with a quick setup. The official documentation is your best friend here, but here's a streamlined version to get you up and running.

Prerequisites:

  • A running Kubernetes cluster (like Minikube or a cloud-based one).
  • kubectl installed and configured to talk to your cluster.

Installation:

The ArgoCD documentation provides the most up-to-date installation commands. Here's the gist of it:

  1. Create a namespace for ArgoCD:

    bash
    kubectl create namespace argocd
  2. Apply the ArgoCD installation manifests:

    bash
    kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

    This command pulls the latest stable manifests from the official ArgoCD GitHub repository and applies them to your cluster. This will create all the necessary Deployments, Services, and Custom Resource Definitions (CRDs) for ArgoCD to run.

  3. Access the ArgoCD API Server:

    By default, the ArgoCD API server is not exposed with an external IP. For a quick test, you can use port forwarding:

    bash
    kubectl port-forward svc/argocd-server -n argocd 8080:443

    Now you can access the ArgoCD UI at https://localhost:8080.

  4. Log in to the ArgoCD UI:

    The initial password for the admin user is automatically generated and stored in a Kubernetes secret. You can retrieve it with this command:

    bash
    kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d

    Use admin as the username and the retrieved password to log in.

A Simple ArgoCD Application:

Now for the fun part! Let's tell ArgoCD to deploy a sample application.

  1. Create an Application manifest:

    Create a file named my-app.yaml:

    yaml
    apiVersion: argoproj.io/v1alpha1
    kind: Application
    metadata:
      name: my-app
      namespace: argocd
    spec:
      project: default
      source:
        repoURL: 'https://github.com/argoproj/argocd-example-apps.git'
        path: guestbook
        targetRevision: HEAD
      destination:
        server: 'https://kubernetes.default.svc'
        namespace: default
  2. Apply the Application manifest:

    bash
    kubectl apply -f my-app.yaml -n argocd

Now, if you go to the ArgoCD UI, you'll see a new application called my-app. ArgoCD will automatically sync the resources defined in the guestbook directory of the example repository to your default namespace. You can explore the UI to see the status of all the deployed resources.

If you were to now go and manually delete a service that ArgoCD just created, you would see the application status in the UI change to OutOfSync. If you have auto-sync enabled, ArgoCD would immediately recreate that service for you. It's like having a vigilant guardian for your cluster!


4. Managing Multiple Environments (Dev, Staging, Prod) 🌳

In the real world, you're not just deploying to one environment. You'll likely have at least a development, staging, and production environment. So how does GitOps handle this?

The most common and effective pattern is to use different branches or directories in your Git repository to represent different environments.

Let's imagine you have a configuration repository. A popular strategy is the "directory-per-environment" approach:

stylus
β”œβ”€β”€ my-app
β”‚   β”œβ”€β”€ base
β”‚   β”‚   β”œβ”€β”€ deployment.yaml
β”‚   β”‚   β”œβ”€β”€ service.yaml
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ overlays
β”‚   β”‚   β”œβ”€β”€ dev
β”‚   β”‚   β”‚   β”œβ”€β”€ configmap.yaml
β”‚   β”‚   β”‚   └── patch.yaml
β”‚   β”‚   β”œβ”€β”€ staging
β”‚   β”‚   β”‚   β”œβ”€β”€ configmap.yaml
β”‚   β”‚   β”‚   └── patch.yaml
β”‚   β”‚   └── prod
β”‚   β”‚       β”œβ”€β”€ configmap.yaml
β”‚   β”‚       └── patch.yaml

In this structure:

  • The base directory contains the common Kubernetes manifests for your application.
  • The overlays directory has subdirectories for each environment. These contain environment-specific configurations, like different replica counts, resource limits, or ConfigMaps.

Tools like Kustomize are fantastic for this. Kustomize allows you to define a base configuration and then apply "patches" or "overlays" for each environment without duplicating all the YAML.

You would then create separate ArgoCD applications for each environment, pointing to the corresponding directory in your Git repository.

  • my-app-dev ArgoCD application points to my-app/overlays/dev.
  • my-app-staging ArgoCD application points to my-app/overlays/staging.
  • my-app-prod ArgoCD application points to my-app/overlays/prod.

The Promotion Workflow:

Promoting changes from one environment to the next becomes a simple matter of updating the Git repository.

  1. A developer makes a change and it gets deployed to the dev environment.
  2. After testing, to promote to staging, you would create a pull request to update the staging configuration, perhaps by cherry-picking the commit from the dev branch or by updating an image tag in the staging overlay.
  3. Once that PR is merged, ArgoCD automatically deploys the change to the staging environment.
  4. The process is the same for promoting to production.

This makes the promotion process transparent, auditable, and easy to automate.


Extra Reading and Resources πŸ“š

Challenge

Challenge: Configure ArgoCD for a Multi-Environment Application

You are a DevOps engineer responsible for setting up continuous delivery for a new application called guestbook using a GitOps workflow with ArgoCD. The application's Kubernetes manifests are managed in a single Git repository at https://github.com/argoproj/argocd-example-apps.git.

Your task is to create the ArgoCD Application manifests to deploy the guestbook application to two different environments: staging and production.

Requirements:

  1. Create two ArgoCD Application resources in a single YAML file, separated by ---.
  2. Both applications will be deployed into the argocd namespace on the same Kubernetes cluster, which is identified by the server URL https://kubernetes.default.svc.

Staging Application Details:

  • Metadata Name: guestbook-staging
  • Project: default
  • Destination Namespace: staging
  • Source Repository URL: https://github.com/argoproj/argocd-example-apps.git
  • Source Path: guestbook
  • Source Target Revision: HEAD
  • Sync Policy: Must be fully automated. The application state should automatically sync when changes are detected in Git, and any manual changes in the cluster (drift) should be automatically corrected (self-heal).

Production Application Details:

  • Metadata Name: guestbook-prod
  • Project: default
  • Destination Namespace: production
  • Source Repository URL: https://github.com/argoproj/argocd-example-apps.git
  • Source Path: guestbook
  • Source Target Revision: Pin to a specific, stable Git tag: v0.1.0
  • Sync Policy: Must be manual. Changes from Git should not be applied automatically. The sync must be triggered manually by an operator.

Expected result

A single, valid YAML file containing two ArgoCD Application resources.

First Resource (Staging):

  • apiVersion should be argoproj.io/v1alpha1.
  • kind should be Application.
  • metadata.name should be guestbook-staging.
  • metadata.namespace should be argocd.
  • spec.project should be default.
  • spec.source should correctly specify the repoURL, path, and targetRevision as HEAD.
  • spec.destination should specify the server and namespace as staging.
  • spec.syncPolicy.automated block must be present and configured with prune: true and selfHeal: true.

Second Resource (Production):

  • Separated from the first resource by ---.
  • apiVersion should be argoproj.io/v1alpha1.
  • kind should be Application.
  • metadata.name should be guestbook-prod.
  • metadata.namespace should be argocd.
  • spec.project should be default.
  • spec.source should correctly specify the repoURL, path, and targetRevision as the git tag v0.1.0.
  • spec.destination should specify the server and namespace as production.
  • spec.syncPolicy should be present but the automated field must be omitted to enforce manual synchronization.
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.