-
-
Save tanelmae/d484c68bd04d65a60bcde7d3deaee073 to your computer and use it in GitHub Desktop.
Switch between kubectl contexts
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
| kctx() { | |
| local CLUSTER_NAME=${1} | |
| if [[ -z $CLUSTER_NAME ]]; then | |
| local OPTIONS=$(kubectl config get-contexts -o name) | |
| OPTIONS+=' EXIT' | |
| local CTX=$(kubectl config current-context) | |
| local NS=$(kubectl config view -o jsonpath="{.contexts[?(@.name=='$CTX')].context.namespace}") | |
| if [[ -z $NS ]]; then | |
| NS="default" | |
| fi | |
| echo "Current ctx/ns: $CTX/$NS" | |
| echo "Switch to which context? (or EXIT)" | |
| select opt in $OPTIONS; do | |
| if [ "$opt" = "EXIT" ]; then | |
| echo "Staying in the current context" | |
| else | |
| kubectl config use-context "$opt" | |
| fi | |
| break | |
| done | |
| else | |
| kubectl config use-context "$CLUSTER_NAME" | |
| fi | |
| CTX=$(kubectl config current-context) | |
| NS=$(kubectl config view -o jsonpath="{.contexts[?(@.name=='$CTX')].context.namespace}") | |
| if [[ -z $NS ]]; then | |
| NS="default" | |
| fi | |
| echo "Current ctx/ns: $CTX/$NS" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment