Skip to content

Instantly share code, notes, and snippets.

@tanelmae
Created July 1, 2020 08:28
Show Gist options
  • Save tanelmae/32b3658bc9a7b3e83052a9f1fab3f2fb to your computer and use it in GitHub Desktop.
Save tanelmae/32b3658bc9a7b3e83052a9f1fab3f2fb to your computer and use it in GitHub Desktop.
Switch between Kubernetes namespaces
kns() {
local CTX=$(kubectl config current-context)
local NAMESPACE=${1}
if [[ -z $NAMESPACE ]]; then
local OPTIONS=$(kubectl get namespaces -o jsonpath='{range .items[*].metadata.name}{@}{"\n"}{end}')
OPTIONS+=' EXIT'
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 namespace? (or EXIT)"
select opt in $OPTIONS; do
if [ "$opt" = "EXIT" ]; then
echo "Staying in the current namespace"
else
kubectl config set-context "$CTX" --namespace "$opt"
fi
break
done
else
kubectl config set-context "$CTX" --namespace "$NAMESPACE"
fi
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