Skip to content

Instantly share code, notes, and snippets.

@danrl
Created September 5, 2017 15:29
Show Gist options
  • Save danrl/0138e8c97d48570b2cfa22fbe97ee8da to your computer and use it in GitHub Desktop.
Save danrl/0138e8c97d48570b2cfa22fbe97ee8da to your computer and use it in GitHub Desktop.
Google Cloud Platform Kubernetes cluster switcher
#!/bin/bash
# caution: quick hack!
# -- project selection
PROJECT_IDS=()
PROJECT_NAMES=()
IFS_ORIG=$IFS
IFS='
'
for LINE in $(gcloud projects list 2>/dev/null | tail -n +2)
do
IFS=$IFS_ORIG
LINE=($LINE)
PROJECT_IDS+=(${LINE[0]})
PROJECT_NAMES+=(${LINE[1]})
done
IFS=$IFS_ORIG
PROJECT_SELECTION=0
while [[ $PROJECT_SELECTION -lt 1 || $PROJECT_SELECTION -gt ${#PROJECT_IDS[@]} ]]
do
echo "Projects:"
for ((i=0; i < ${#PROJECT_IDS[@]}; i++))
do
printf "%3s: %-30s (%s)\n" "$((i + 1))" "${PROJECT_NAMES[${i}]}" "${PROJECT_IDS[${i}]}"
done
echo -n "Select project: "
read PROJECT_SELECTION
done
((PROJECT_SELECTION--))
gcloud config set project ${PROJECT_IDS[${PROJECT_SELECTION}]}
# --- cluster selection
CLUSTER_NAMES=()
CLUSTER_ZONES=()
IFS_ORIG=$IFS
IFS='
'
for LINE in $(gcloud container clusters list 2>/dev/null | tail -n +2)
do
IFS=$IFS_ORIG
LINE=($LINE)
CLUSTER_NAMES+=(${LINE[0]})
CLUSTER_ZONES+=(${LINE[1]})
done
IFS=$IFS_ORIG
CLUSTER_SELECTION=0
if [ "${#CLUSTER_NAMES[@]}" -eq 1 ]
then
echo "Automatically selecting the only cluster in project ${PROJECT_IDS[${PROJECT_SELECTION}]}."
CLUSTER_SELECTION=1
fi
while [[ $CLUSTER_SELECTION -lt 1 || $CLUSTER_SELECTION -gt ${#CLUSTER_NAMES[@]} ]]
do
echo "Cluster:"
for ((i=0; i < ${#CLUSTER_NAMES[@]}; i++))
do
printf "%3s: %-30s (%s)\n" "$((i + 1))" "${CLUSTER_NAMES[${i}]}" "${CLUSTER_ZONES[${i}]}"
done
echo -n "Select cluster: "
read CLUSTER_SELECTION
done
((CLUSTER_SELECTION--))
gcloud container clusters get-credentials ${CLUSTER_NAMES[${CLUSTER_SELECTION}]} -z ${CLUSTER_ZONES[${CLUSTER_SELECTION}]}
echo ">>> You are now on ${PROJECT_IDS[${PROJECT_SELECTION}]}/${CLUSTER_NAMES[${CLUSTER_SELECTION}]} <<<"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment