• +43 660 1453541
  • contact@germaniumhq.com

How to Easily Switch Namespaces in Kubernetes


How to Easily Switch Namespaces in Kubernetes

What if instead of writing insanely long commands in the terminal to find out the namespace we’re working on, there would be a command for it? Let’s say kubens? With bash completion? Of course.

kubens in action

I don’t blame you if you don’t know, I can’t remember the syntax of this by heart either, but to query the name of the current namespace you need to do:

kubectl config view -o jsonpath={.contexts[].context.namespace}

And to change the current namespace:

kubectl config set-context $(kubectl config current-context) --namespace=newns

Yeah, that’s not pretty.

Now let’s combine these commands in a small bash script:

#!/usr/bin/env bash

if [[ "$1" == "" ]]; then
    CURRENT_NAMESPACE=$(kubectl config view -o jsonpath={.contexts[].context.namespace})
    echo "You need to specify the namespace name."
    echo "Current namespace: $CURRENT_NAMESPACE"
    exit 1
fi # [[ "$1" == "" ]]

kubectl config set-context $(kubectl config current-context) --namespace=$1

This will take care of both showing us the current namespace, by just typing kubens, or switching to a particular namespace by calling: kubens my-ns. Since most of the time we’ll want to switch the namespace, due to our trusty memory, maybe it would be nice to have autocompletion, so when we type kubens <TAB> we get the possible namespaces we can switch to.

#!/usr/bin/env bash

__kubens_complete() {
    ITEMS=$(kubectl get ns -o jsonpath='{.items[*].metadata.name}')
    COMPREPLY=($(compgen -W "$ITEMS" "${COMP_WORDS[1]}"))
}

complete -F __kubens_complete kubens

Nice. Now we only need to source it and we’re done. Add at the end of your $HOME/.bashrc:

. kubens.bash.complete.sh

Enjoy your Kubernetes and to something amazing :D.