Kubernetes: BASH function to change namespace

So when working with a lot of different namespaces in Kubernetes and you only know the “oc project” command from OpenShift, you start to miss an easy way to change namespaces in Kubernetes.

The official documentation to switch namespaces proposes something like this:

$ kubectl config set-context $(kubectl config current-context) --namespace=<insert-namespace-name-here>

Not something that I want to type regularly. First I tried to create a BASH alias or something, which did not work. So I looked around for BASH functions. I found that Jon Whitcraft proposed a nice BASH function in a GitHub issue. I lightly modified this and placed this in my own .bashrc file:

function kubectlns() {
  ctx=`kubectl config current-context`
  ns=$1

  # verify that the namespace exists
  ns=`kubectl get namespace $1 --no-headers --output=go-template={{.metadata.name}} 2>/dev/null`
  if [ -z "${ns}" ]; then
    echo "Namespace (${1}) not found, using default"
    ns="default"
  fi

  kubectl config set-context ${ctx} --namespace="${ns}"
}

So to change your namespace, use something like this:

$ kubectlns simon
Context "kubernetes-admin@kubernetes" modified.

Nice and short.

Hello world

My name is Simon Krenger, I am a Technical Account Manager (TAM) at Red Hat. I advise our customers in using Kubernetes, Containers, Linux and Open Source.

Elsewhere

  1. GitHub
  2. LinkedIn
  3. GitLab