Get Rid of Namespace Parameters When Working with Kubernetes

A few convenient ways to save you from typing -n or --namespace with every single kubectl command.

[ kubernetes ]

Have you grown sick and tired of typing kubectl -n someverylongnamespacename all day long?

There’s a few ways to ditch the namespace flag from every. single. command. you issue. The best choice for you, depends on the number of clusters you work with, their stability and your workflows.

Create a Shell Alias

If you just want to type less and are working with a single namespace, you could just create an alias in your .bashrc, .zshrc or similar. It’s not fancy, but gets the job done.

You could do it in one line:

alias k='kubectl -n NAMESPACE_NAME'

And use it like this:

$ k get pods

Keeping it simple and practical. If you have multiple namespaces, the next method will serve you better however.

Create a Context

If you are working in a small number of stable, well defined namespaces, you can use contexts to your advantage. This way, you can specify a user, cluster and namespace to use for all subsequent commands.

You can get your current context with

$ kubectl config current-context

And create a new one using a simple command:

$ kubectl config set-context CONTEXT_NAME --namespace=NAMESPACE_NAME \
  --cluster=CLUSTER_NAME \

All of the above upper-case names should be replaced by you with ones which you need. Look the values up in your .kube/config file. They don’t need to be upper-case and underscores of course, here’s an example:

$ kubectl config set-context monitoring --namespace=monitoring --cluster=kubernetes --user=kubernetes-admin

From now on, you can switch to that context at any future time with:

$ kubectl config use-context CONTEXT_NAME

Now all your future commands will be issued in that namespace, without specifying a -n NAMESPACE_NAME or --namespace=NAMESPACE_NAME flag. The current context is saved in your config file, and will persist until you change it again.


If you don’t mind installing and using helper tools, then kubens and kubectx are worth checking out. You can use them to switch between contexts and namespaces smoothly, with a nice ux.

Get them via a method which suits your OS described on the GitHub repo of the project.

An example usage pattern could be:

$ kubectx CONTEXT_NAME
$ kubectx -
# back to the previous context

Learn more about Kubernetes!

Do you want more actionable, useful and understandable resources about Kubernetes to help you learn quicker and save time? Sign up to my mailing list!