Mike Barkas

Software Technologies

Mike Barkas

Mike Barkas

Software Technologies

Kubernetes Contexts

November 11, 2024

The kubectl command line program uses a configuration file to determine what it is controlling.

The configuration file is normally located at: ${HOME}/.kube/config.

Your config file will contain a list of clusters, list of contexts, users, and other informaton.

To see what is in your config file use kubectl config view

Using kubectl you are able to view the configuration, set the namespace, get the current namespace, and change clusters. You can also use kubectl to edit the config file to make custom contexts.

The kubectl command uses a what is called a context in which you target your commands.

The common items you would change in a context is the cluster and the namespace. You would also want to name each context you create.

This is an example of a default context:

contexts:
- context:
  cluster: default
  namespace: default
  user: default
name: default

Notice the namespace is default. This is why when you type commands with kubectl you only see the default namespace items.

Using kubectl, let’s create a custom context to focus on the kube-system namespace as an example.

$ kubectl config set-context kubesys --namespace=kube-system --user=default --cluster=default

Note: Your user and cluster may have a different name than default.

Let’s see a list of our contexts.

$ kubectl config get-contexts
CURRENT   NAME       CLUSTER   AUTHINFO   NAMESPACE
*         default    default   default
          kubesys    default   default    kube-system

Now we have a new context called kubesys and it uses the kube-system namespace. This context still uses the same cluster only the namespace has changed.

Check what your current context is.

$ kubectl config current-context
default

Now lets change to our new context kubesys.

$ kubectl config use-context kubesys
Switched to context "kubesys".

Now you will be looking at the resources in the kube-system namespace and will not need to add -n kube-system to your commands.

Typing the long config context commands is not easy to remember, so lets create an alias.

alias kcc='kubectl config current-context'
alias kuc='kubectl config use-context'

Now switching between namespaces is easy.

$ kuc kubesys
Switched to context "kubesys".

Creating custom contexts and only changing the namespace is convenient when working on multiple projects or separating prod and staging resources. You can also create custom contexts to target remote clusters.

The kubectl config has many options. Read the kubernetes docs for information.