Automating Kubernetes Deployments with GitHub Actions

In today’s DevOps world, automation is key to faster and more reliable deployments. Instead of manually applying Kubernetes manifests, we can use GitHub Actions to trigger deployments automatically whenever we push code.

What We Built Today?

  • A complete GitHub Actions pipeline for Kubernetes deployments
  • End-to-end automation from code commit to deployment
  • Secure & efficient setup using GitHub Secrets

Key Challenges We Solved:

  • How to integrate GitHub Actions with Kubernetes?
  • Ensuring deployments are non-root and secure
  • Handling GitHub Secrets for secure kubeconfig access Kubernetes Deployment YAML

Here’s the Kubernetes deployment we used today:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
  namespace: default
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      securityContext:
        runAsNonRoot: true
      containers:
        - name: myapp
          image: nginxinc/nginx-unprivileged:latest
          ports:
            - containerPort: 80
          securityContext:
            runAsNonRoot: true
            readOnlyRootFilesystem: true
          volumeMounts:
            - mountPath: /var/cache/nginx
              name: cache-volume
            - mountPath: /tmp
              name: tmp-volume
      volumes:
        - name: cache-volume
          emptyDir: {}
        - name: tmp-volume
          emptyDir: {}
Click Here to Copy YAML
  • Runs as a non-root user
  • Read-only root filesystem for security
  • Uses nginx-unprivileged for better compliance Setting Up GitHub Actions for Kubernetes

To automate deployment, we used this GitHub Actions workflow:

name: Deploy to Kubernetes

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code
        uses: actions/checkout@v3

      - name: Set up kubectl
        uses: azure/setup-kubectl@v3
        with:
          version: latest

      - name: Configure Kubernetes Cluster
        run: |
          echo "${{ secrets.KUBECONFIG }}" | base64 --decode > kubeconfig
          export KUBECONFIG=kubeconfig

      - name: Deploy to Kubernetes
        run: kubectl apply -f deploy.yaml
Click Here to Copy YAML

What It Does?

  • Triggers on every git push to main
  • Sets up kubectl to interact with the cluster
  • Uses GitHub Secrets (KUBECONFIG) for secure authentication
  • Deploys the latest changes to Kubernetes automatically

Why This Matters?

  • No more manual deployments
  • Instant updates on every push
  • Security-first approach with GitHub Secrets

Do you automate your Kubernetes deployments? Let’s discuss best practices in the comments! 👇

Leave a comment