Last active
April 26, 2023 20:54
-
-
Save robkooper/7d8590aff8d11ee0a3509dcc06bef1ae to your computer and use it in GitHub Desktop.
Connect to rancher and get all your kubeconfigs into a single config file. This will save your docker-desktop, rancher-desktop and rancher (if any exist) configurations. This will cleanup your api keys in rancher as well.
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
#!/bin/bash | |
CURRENT=$(kubectl config current-context) | |
USERTOKEN="supersecretapitoken" | |
RANCHERENDPOINT=https://gonzo-rancher.ncsa.illinois.edu/v3 | |
CLUSTERS=$(curl -s -u $USERTOKEN $RANCHERENDPOINT/clusters -H 'content-type: application/json' | jq -c '.data[] | {"name":.name, "id": .id}' | sort) | |
# cleanup | |
rm -f kubeconfig | |
touch kubeconfig | |
# remove old tokens | |
for token in $(curl -s -u "${USERTOKEN}" ${RANCHERENDPOINT}/tokens | jq -r '.data[] | select (.description == "Kubeconfig token").id'); do | |
curl -s -X DELETE -u "${USERTOKEN}" ${RANCHERENDPOINT}/tokens/${token} | |
done | |
# save special clusters | |
for CLUSTERID in rancher rancher-desktop docker-desktop; do | |
kubectl config use-context ${CLUSTERID} 2>/dev/null && ( | |
echo "Getting config for ${CLUSTERID}" | |
kubectl config view --minify --raw > ${CLUSTERID}.kubeconfig | |
mv kubeconfig kubeconfig.old | |
export KUBECONFIG=kubeconfig.old:${CLUSTERID}.kubeconfig | |
kubectl config view --flatten --merge > kubeconfig | |
rm ${CLUSTERID}.kubeconfig kubeconfig.old | |
) | |
done | |
# get all clusters from rancher | |
for ROW in $CLUSTERS; do | |
CLUSTERID=$(echo $ROW | jq -r .id) | |
CLUSTERNAME=$(echo $ROW | jq -r .name) | |
echo "Getting config for ${CLUSTERID} : ${CLUSTERNAME}" | |
curl -s -u $USERTOKEN $RANCHERENDPOINT/clusters/$CLUSTERID?action=generateKubeconfig -X POST -H 'content-type: application/json' | jq -r .config > ${CLUSTERID}.kubeconfig | |
mv kubeconfig kubeconfig.old | |
export KUBECONFIG=kubeconfig.old:${CLUSTERID}.kubeconfig | |
kubectl config view --flatten --merge > kubeconfig | |
rm ${CLUSTERID}.kubeconfig kubeconfig.old | |
done | |
mv kubeconfig ~/.kube/config | |
chmod 600 ~/.kube/config | |
unset KUBECONFIG | |
kubectl config use-context ${CURRENT} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment