How to Backup your Kubernetes Cluster using Bash

Kubernetes

In order to save all manifests, create a BASH script by running:

nano k8s.sh

With the following contents:

#!/bin/bash
 
DIR='k8s-manifests/namespaces'
 
mkdir -p $DIR
 
for NAMESPACE in $(kubectl get -o=name namespaces | cut -d '/' -f2)
do
    for TYPE in $(kubectl get -n $NAMESPACE -o=name pvc,configmap,serviceaccount,secret,ingress,service,deployment,statefulset,hpa,job,cronjob)
    do
        mkdir -p $(dirname $DIR/$NAMESPACE/$TYPE)
        kubectl get -n $NAMESPACE -o=yaml $TYPE > $DIR/$NAMESPACE/$TYPE.yaml
    done
done

Add the execution bit and run it:

chmod a+x ./k8s.sh

After executing in the current directory in the folder “k8s-manifests” will be saved all manifests ordered by namespaces and types.

By Dennis Otugo

Dennis Otugo is a Consultant at Bantrain, and loves all things DevOps. In his role, he enables enterprise customers in their digital transformation journey and helps architect cloud-native solutions