Last active
July 11, 2024 10:57
-
-
Save negz/c3ee465b48306593f16c523a22015bec to your computer and use it in GitHub Desktop.
Dump Kubernetes cluster resources as YAML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -e | |
CONTEXT="$1" | |
if [[ -z ${CONTEXT} ]]; then | |
echo "Usage: $0 KUBE-CONTEXT" | |
exit 1 | |
fi | |
NAMESPACES=$(kubectl --context ${CONTEXT} get -o json namespaces|jq '.items[].metadata.name'|sed "s/\"//g") | |
RESOURCES="configmap secret daemonset deployment service hpa" | |
for ns in ${NAMESPACES};do | |
for resource in ${RESOURCES};do | |
rsrcs=$(kubectl --context ${CONTEXT} -n ${ns} get -o json ${resource}|jq '.items[].metadata.name'|sed "s/\"//g") | |
for r in ${rsrcs};do | |
dir="${CONTEXT}/${ns}/${resource}" | |
mkdir -p "${dir}" | |
kubectl --context ${CONTEXT} -n ${ns} get -o yaml ${resource} ${r} > "${dir}/${r}.yaml" | |
done | |
done | |
done |
sweet! If you want all resources you could do:
RESOURCES=$(kubectl api-resources --namespaced -o name | tr "\n" " ")
and namespaces without jq
:
kubectl get ns -o jsonpath="{.items[*].metadata.name}"
Quick jq
tip:
If you use -r
then you won't need to strip quotes with sed
.
... | jq '.items[].metadata.name' | sed "s/\"//g"
# is equivalent to
... | jq -r '.items[].metadata.name'
Quote from man page:
o --raw-output / -r:
With this option, if the filter's result is a string then it will be written
directly to standard output rather than being formatted as a JSON string
with quotes. This can be useful for making jq filters talk to non-JSON-based
systems.
Saved me from a huge headache today
Thanks!
You can try this script
This is a great script. I simply added statefulset to line 13 to get them too. :)
what is context?
what is context?
The context of the kubernetes "connection", check the ~/.kube/config file for more information.
If you don't know, just grab your current kubernetes context (ie: if you run minikube or a single-node this is what you want):
cat ~/.kube/config | grep current-context
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome