Get Rid of Namespace Parameters When Working with Kubernetes

TAGS: K8S, KUBECTL

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 \
  --user=USER_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.

Fancier

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
Subscribe to my newsletter!
You'll get notified via e-mail when new articles are published. I mostly write about Docker, Kubernetes, automation and building stuff on the web. Sometimes other topics sneak in as well.

Your e-mail address will be used to send out summary emails about new articles, at most weekly. You can unsubscribe from the newsletter at any time.

Für den Versand unserer Newsletter nutzen wir rapidmail. Mit Ihrer Anmeldung stimmen Sie zu, dass die eingegebenen Daten an rapidmail übermittelt werden. Beachten Sie bitte auch die AGB und Datenschutzbestimmungen .

vsupalov.com

© 2024 vsupalov.com. All rights reserved.