If you're here, it's likely because you're tired of typing something like kubectl get pods --namespace mynamespace and you would rather be able to just type kubectl get pods and have kubectl just simply know that you're interacting with a particular namespace. Here's how you set the working namespace for kubectl:

kubectl config set-context --current --namespace=mynamespace
Change the Namespace Kubectl Uses

Now when you run commands with Kubectl, you will be interacting with the myspace namespace by default. Of course, you should change "myspace" to whatever namespace you need.

Changing Contexts Quick and Often

The above command is great. It accomplishes our purpose, but it could be extremely annoying to type all of that out regularly. Instead, you can either:

Option 1: Create a Function

To do this, you will simply define a bash function and place it in ~/.bashrc so that it persists between sessions. Here's the line that you want to add:

set-ns () { kubectl config set-context --current --namespace="[email protected]"}
Simplify Namespace Switching with this Bash Function

Then you can simply run this command to set your namespace: set-ns mynamespace

Option 2: Create a Script

To do this, you can create a file called set-ns, make it executable by running chmod +x set-ns, and place it in a location that is in your PATH (or add that location to your path). The contents of that file will be:

kubectl config set-context --current --namespace=$1
Simplify Namespace Switching with this Bash Script

And similar to option 1, you can now run this command to set your namespace: set-ns mynamespace

Checking your Kubectl Context Namespace

Curious what namespace you're currently interacting with? Run this command to list all of your contexts:

kubectl config get-contexts
List All Kubectl Contexts

That will show you all of your contexts and their relevant information, including their namespace.

But which context are you using in that list? Run this to find out:

kubectl config current-context
Discover Which Context You're Currently Using

Happy Kuberneting!