Created
September 21, 2023 17:51
-
-
Save pjaudiomv/81fc17e918eb15610d6f9966044f551b to your computer and use it in GitHub Desktop.
Kubeconfig Context Switcher
This file contains hidden or 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
#!/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