Skip to content

Instantly share code, notes, and snippets.

@pjaudiomv
Created September 21, 2023 17:51
Show Gist options
  • Save pjaudiomv/81fc17e918eb15610d6f9966044f551b to your computer and use it in GitHub Desktop.
Save pjaudiomv/81fc17e918eb15610d6f9966044f551b to your computer and use it in GitHub Desktop.
Kubeconfig Context Switcher
#!/usr/bin/env bash
usage () {
echo "Usage: kx [OPERATION]"
echo " -h Help. Displays this message."
echo " -l list contexts"
echo " -c get current context"
echo " -s set context"
echo " -d delete context"
}
list_contexts() {
select context in $(kubectl config get-contexts -o=name | sort -n) exit; do
case $context in
exit) echo "exiting"
break ;;
*) context_val=$context;
break ;;
esac
done
}
confirm() {
read -r -p "${1:-Are you sure? [y/N]} " response
case "$response" in
[yY][eE][sS]|[yY])
true
;;
*)
false
;;
esac
}
[ $# -eq 0 ] && usage
while getopts ":lsdch" opt; do
case "${opt}" in
l)
kubectl config get-contexts -o=name | sort -n
;;
s)
list_contexts
kubectl config use-context "${context_val}"
;;
c)
kubectl config current-context
;;
d)
list_contexts
confirm "Are you sure you want to delete ${context_val}? [y/N]"&& \
kubectl config delete-context "${context_val}" && \
kubectl config delete-cluster "${context_val}" && \
kubectl config delete-user "${context_val}"
;;
\?)
>&2 echo "Invalid option: $OPTARG."
usage
;;
:)
>&2 echo "Missing argument: $OPTARG requires an argument."
usage
;;
h | *)
usage
exit 0
;;
esac
done
shift $((OPTIND -1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment