Skip to content

Instantly share code, notes, and snippets.

@walkerjam
Last active December 10, 2018 15:43
Show Gist options
  • Save walkerjam/1a9af21cc71d5e88c0498d5c5319cafe to your computer and use it in GitHub Desktop.
Save walkerjam/1a9af21cc71d5e88c0498d5c5319cafe to your computer and use it in GitHub Desktop.
Change kubernetes cluster
#!/bin/bash
#
CUR_CLUSTER=$(basename $(readlink -f $(find ~/.kube -type l -name "config")) | awk -F'.' '{ print $2 }')
NEW_CLUSTER=
while :; do
case $1 in
-h|-\?|--help)
cat << EOF
Usage: ${0##*/} [-h] [CLUSTER]
Change current Kubernetes cluster.
-h display this help and exit
EOF
exit
;;
*)
if [[ -n "$1" ]]; then
NEW_CLUSTER="$1"
fi
esac
shift
if [[ -z $1 ]]; then
break;
fi
done
if [ -z "$NEW_CLUSTER" ]; then
echo "Select a new cluster:"
echo
CLUSTERS=( $(find ~/.kube -type f -name "config.*" -exec basename {} \; | awk -F'.' '{ print $2 }' | sort) )
CLUSTER_OPTS=()
CLUSTER_LABELS=()
for CLUSTER in "${CLUSTERS[@]}"; do
CLUSTER_OPTS+=("$CLUSTER")
if [[ $CLUSTER == $CUR_CLUSTER ]]; then
CLUSTER_LABELS+=("$(tput setaf 6)$CLUSTER$(tput sgr0) (current)")
else
CLUSTER_LABELS+=("$CLUSTER")
fi
done
I=0
for LABEL in "${CLUSTER_LABELS[@]}"; do
printf '%s\n' "$((++I))) $LABEL"
done >&2
NUM_ITEMS=${#CLUSTER_LABELS[@]}
PS3="$(tput setaf 6) > Cluster: $(tput sgr0)"
while :; do
printf %s "${PS3}" >&2
read -r INDEX
# Make sure that the input is either empty or that a valid index was entered.
[[ -z $INDEX ]] && break # empty input
(( INDEX >= 1 && INDEX <= NUM_ITEMS )) 2>/dev/null || { continue; }
break
done
if [[ -n $INDEX ]]; then
NEW_CLUSTER="${CLUSTER_OPTS[$INDEX - 1]}"
else
NEW_CLUSTER=$CUR_CLUSTER
fi
fi
if [[ -n $NEW_CLUSTER ]]; then
if [[ $CUR_CLUSTER != $NEW_CLUSTER ]]; then
rm -f ~/.kube/config
ln -s ~/.kube/config.$NEW_CLUSTER ~/.kube/config
echo "Set cluster to $(tput setaf 6)$NEW_CLUSTER$(tput sgr0)"
else
echo "Current cluster $(tput setaf 6)$CUR_CLUSTER$(tput sgr0) (not changed)"
fi
echo
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment