Skip to content

Instantly share code, notes, and snippets.

@taxilian
Created September 8, 2021 21:12
Show Gist options
  • Save taxilian/9aeb80f02d28591f0070cf779e3ff763 to your computer and use it in GitHub Desktop.
Save taxilian/9aeb80f02d28591f0070cf779e3ff763 to your computer and use it in GitHub Desktop.
Bash script to export all kubernetes resources as YAML files in a directory structure
#!/bin/bash
allCRDs=$(kubectl get crd -o name | cut -d '/' -f 2)
nsCRD=""
clusterCRD=""
for crd in $allCRDs; do
scope=$(kubectl describe crd $crd | grep "Scope" | cut -d ':' -f 2 | sed 's/^ *//g')
if [ "$scope" == "Namespaced" ]; then
echo "$crd is namespaced"
nsCRD="${nsCRD} ${crd}"
else
echo "$crd is cluster-wide"
clusterCRD="${clusterCRD} ${crd}"
fi
done
nsCrdList=$(echo $nsCRD | tr ' ' ',')
clusterCrdList=$(echo $clusterCRD | tr ' ' ',')
echo "Exporting namespaced resources:"
for ns in $(kubectl get ns --no-headers | cut -d " " -f1); do
echo "Found namespace $ns"
mkdir -p -v "$ns"
pushd "$ns"
for n in $(kubectl -n $ns get -o=name pvc,configmap,serviceaccount,secret,ingress,service,deployment,statefulset,hpa,job,cronjob,$nsCrdList); do
mkdir -p $(dirname $n)
kubectl -n $ns get -o=yaml "$n" > "$n.yaml"
echo Exporting ${n}.yaml
done
popd
done
echo "Exporting cluster-wide resources:"
for n in $(kubectl get -o=name $clusterCrdList); do
mkdir -p _cluster/$(dirname $n)
kubectl get -o=yaml "$n" > "_cluster/$n.yaml"
echo Exporting _cluster/${n}.yaml
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment