Skip to content

Instantly share code, notes, and snippets.

@tanelmae
Last active July 1, 2020 08:29
Show Gist options
  • Select an option

  • Save tanelmae/d484c68bd04d65a60bcde7d3deaee073 to your computer and use it in GitHub Desktop.

Select an option

Save tanelmae/d484c68bd04d65a60bcde7d3deaee073 to your computer and use it in GitHub Desktop.
Switch between kubectl contexts
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