Skip to content

Instantly share code, notes, and snippets.

@kbristow
Last active February 20, 2023 07:22
Show Gist options
  • Select an option

  • Save kbristow/887b38a20cf83d525eb760478a78f426 to your computer and use it in GitHub Desktop.

Select an option

Save kbristow/887b38a20cf83d525eb760478a78f426 to your computer and use it in GitHub Desktop.
Pull all Rancher KubeConfig files locally
#/bin/bash
# $1 rancher url (e.g. https://rancher.my-company.co.za)
# $2 rancher bearer token
# $3 overwrite current kubeconfig with resulting config (default false)
if [[ -z "${1}" ]]; then
echo "Must specify Rancher url to use as first argument (e.g. https://rancher.my-company.co.za). Exiting!"
exit 1
else
RANCHER_URL="${1}"
fi
if [[ -z "${2}" ]]; then
echo "Must specify Rancher auth string to use as second argument (e.g. token-name:token-value). Exiting!"
exit 1
else
RANCHER_AUTH="${2}"
fi
if [[ -z "${3}" ]]; then
OVERWRITE_CURRENT_KUBECONFIG=false
else
OVERWRITE_CURRENT_KUBECONFIG=${3}
fi
rm -rf /tmp/kubeconfigs || true
mkdir -p /tmp/kubeconfigs
echo "Getting all available clusters on provided Rancher instance"
CLUSTERS=$(curl -u "${RANCHER_AUTH}" \
-s \
-X GET \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
"${RANCHER_URL}/v3/clusters" | jq -r '.data[] | "\(.id);\(.appliedSpec.displayName)"')
for CLUSTER_DETAILS_RAW in $CLUSTERS; do
CLUSTER_DETAILS=(${CLUSTER_DETAILS_RAW//;/ } )
if [ "${CLUSTER_DETAILS[0]}" != "local" ]
then
if grep -q "name: ${CLUSTER_DETAILS[1]}" ~/.kube/config; then
echo "KubeConfig for cluster '${CLUSTER_DETAILS[1]}' (${CLUSTER_DETAILS[0]}) already exists locally. Skipping!"
else
echo "Generating KubeConfig for cluster '${CLUSTER_DETAILS[1]}' (${CLUSTER_DETAILS[0]})..."
curl -u "${RANCHER_AUTH}" \
-s \
-X POST \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
"${RANCHER_URL}/v3/clusters/${CLUSTER_DETAILS[0]}?action=generateKubeconfig" | jq .config -r > /tmp/kubeconfigs/${CLUSTER_DETAILS[1]}-kubeconfig.yaml
KUBE_CONFIG_STRING=${KUBE_CONFIG_STRING}/tmp/kubeconfigs/${CLUSTER_DETAILS[1]}-kubeconfig.yaml:
fi
fi
done
echo "Creating merged KubeConfig file..."
HOME_DIR=$(cd ~ && pwd)
KUBECONFIG="${KUBE_CONFIG_STRING}${HOME_DIR}/.kube/config" kubectl config view --flatten > merged-kubconfig.yaml
if [ "$OVERWRITE_CURRENT_KUBECONFIG" = "true" ]
then
cp ~/.kube/config ~/.kube/config.$(date +%s).bkp
mv merged-kubconfig.yaml ~/.kube/config
echo "Merged KubeConfig file generated and replaced default kubeconfig"
else
echo "Merged KubeConfig file generated: $(pwd)/merged-kubconfig.yaml"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment