Skip to content
LF Cert Trainer

Lesson 89 · Section 7: Security

Lesson 89: Kubectx and Kubens: switching clusters and namespaces quickly

What the two command line utilities do, which two kubeconfig fields they edit, the plain kubectl config commands that do the same job, and why you must know those by heart: neither tool is installed in the exam. · 12 min read · 3 min video

Official competency this lesson covers

1/10Kubectx and Kubens
0:00 / 3:17

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

What kubectx and kubens are

An administrator rarely has one cluster. There is a development cluster, a test cluster and production, and each holds dozens of namespaces. kubectl decides where a command goes by reading your kubeconfig file, and changing that decision with kubectl alone takes long commands:

kubectl config use-context prod-eu-west-admin
kubectl config set-context --current --namespace=payments

kubectx and kubens are two small open source utilities, shipped together in one project, that shorten these to a few keystrokes:

kubectx prod-eu-west-admin     # switch context (cluster and user)
kubens payments                # switch the default namespace

They are not part of Kubernetes and kubectl does not need them. They are convenience tools for your own workstation.

How it works

A context is three names

The KubeConfig lesson covers the file in full. For this lesson you need one part of it. A context is a named entry that combines:

  • a cluster: the address of an API server and the certificate authority used to trust it,
  • a user: the credentials sent to that server, such as a client certificate or a token,
  • an optional namespace: the one kubectl uses when you do not pass -n.
A context is three nameswherewhodefault namespaceaddressprovesscopesContext devone entry in kubeconfigclusterdev-clusteruserdev-adminnamespaceshop (optional)API serverhttps://10.0.0.5:6443Credentialscertificate or tokenObjects in shopwhen you omit -n
A context is three names. A context ties a cluster and a user together, plus an optional default namespace. Switching context changes where every later kubectl command goes and who it runs as.

Parts:

  • Context dev (one entry in kubeconfig)
  • cluster (dev-cluster)
  • user (dev-admin)
  • namespace (shop (optional))
  • API server (https://10.0.0.5:6443)
  • Credentials (certificate or token)
  • Objects in shop (when you omit -n)

Connections:

  • Context dev to cluster: where
  • Context dev to user: who
  • Context dev to namespace: default namespace
  • cluster to API server: address
  • user to Credentials: proves
  • namespace to Objects in shop: scopes
apiVersion: v1
kind: Config
current-context: dev            # the active context: kubectx edits this line
contexts:
  - name: dev
    context:
      cluster: dev-cluster
      user: dev-admin
      namespace: shop           # default namespace of "dev": kubens edits this line
  - name: prod
    context:
      cluster: prod-cluster
      user: prod-admin          # no namespace line means "default"

Two details follow from this layout and explain most surprises:

  • The namespace belongs to the context, not to the cluster and not to you. Each context keeps its own value. Switch from dev to prod and the namespace changes with it, to whatever prod has stored.
  • A context can name a namespace that does not exist. The file is only text on your machine. The API server finds out when the next command arrives.

What each tool writes

Each tool edits one field~/.kube/configwriteswritesreadreadrequestkubectx prodpick a contextkubens shoppick a namespacecurrent-contextprodcontext.namespaceshopkubectl get podsreads the file each runprod API serverlists Pods in shop
Each tool edits one field. Neither tool talks to the cluster to switch anything. kubectx rewrites current-context, kubens rewrites the namespace of the current context, and kubectl reads both the next time it runs.

Parts:

  • kubectx prod (pick a context)
  • kubens shop (pick a namespace)
  • current-context (prod), in ~/.kube/config
  • context.namespace (shop), in ~/.kube/config
  • kubectl get pods (reads the file each run)
  • prod API server (lists Pods in shop)

Connections:

  • kubectx prod to current-context: writes
  • kubens shop to context.namespace: writes
  • current-context to kubectl get pods: read
  • context.namespace to kubectl get pods: read
  • kubectl get pods to prod API server: request

kubectl reads the kubeconfig every time it starts. It has no background process and keeps no session. So "being in a context" only means "the file currently says so", and switching is a file edit that takes effect on the next command, in every terminal that uses the same file.

kubens does one thing more than a file edit. Before it switches, it asks the API server whether the namespace exists, and refuses if it does not:

$ kubens shpo
error: no namespace exists with name "shpo"

That check protects you from typos, which plain kubectl config set-context does not. It also means kubens needs a working connection and permission to read namespaces. On a cluster where you may not list namespaces, use kubens shop --force to skip the check, or use kubectl config.

How the dash works

kubectx - and kubens - jump back to the previous context or namespace, like cd - in a shell. A kubeconfig has no field for "previous", so the tools keep their own notes: kubectx stores the last context name in ~/.kube/kubectx, and kubens stores the last namespace of each context in the folder ~/.kube/kubens/ (both move under $XDG_CACHE_HOME when that variable is set).

How the dash remembers where you weresetsold value savedreadsputs dev backreadkubectx prodyou switchcurrent-contextdev becomes prod~/.kube/kubectxprevious: devkubectx -you go backkubectlfollows current-context
How the dash remembers where you were. kubectl has no memory of the previous context. kubectx keeps it in a small file of its own, so kubectx - can swap the two values back and forth.

Parts:

  • kubectx prod (you switch)
  • current-context (dev becomes prod)
  • ~/.kube/kubectx (previous: dev)
  • kubectx - (you go back)
  • kubectl (follows current-context)

Connections:

  • kubectx prod to current-context: sets
  • current-context to ~/.kube/kubectx: old value saved
  • kubectx - to ~/.kube/kubectx: reads
  • kubectx - to current-context: puts dev back
  • current-context to kubectl: read

This is the only feature without a kubectl equivalent. With plain kubectl you look at kubectl config get-contexts and type the name again.

Under the hood · More than one kubeconfig file, and the interactive picker
  • KUBECONFIG is honoured. Both tools read and write the kubeconfig that kubectl would use, including a file named in the KUBECONFIG variable. Support for a KUBECONFIG that lists several files has differed between versions of the tools, so if you merge files that way, test it once or use kubectl config, which always handles it.
  • Interactive mode. If the fuzzy finder fzf is installed, running kubectx or kubens with no argument opens a searchable menu instead of printing a list. Set KUBECTX_IGNORE_FZF=1 to get the plain list back, for example inside a script.
  • As kubectl plugins. Installed through the plugin manager Krew, the same tools are called kubectl ctx and kubectl ns.
  • Shells bound to one context. Recent releases add kubectx --shell <name>, which opens a sub-shell that uses one context without touching the kubeconfig your other terminals share, and --readonly for a shell that can only read. Check kubectx --help to see whether your version has them.

The kubectl equivalents

Every row on the left is a convenience. Every row on the right works on any machine that has kubectl, including the exam hosts.

TaskWith the toolsWith plain kubectl
List contextskubectxkubectl config get-contexts
Show the current contextkubectx -ckubectl config current-context
Switch contextkubectx prodkubectl config use-context prod
Go back to the previous contextkubectx -No equivalent: run use-context with the old name
Rename a contextkubectx new=oldkubectl config rename-context old new
Delete a context entrykubectx -d oldkubectl config delete-context old
Clear the current contextkubectx -ukubectl config unset current-context
List namespaceskubenskubectl get namespaces
Show the current namespacekubens -ckubectl config view --minify -o jsonpath='{..namespace}'
Switch namespacekubens shopkubectl config set-context --current --namespace=shop
Go back to the previous namespacekubens -No equivalent: run set-context with the old name

Watch the argument order when you rename: kubectx takes new=old, while kubectl config rename-context takes old new.

Using it

Example · Install and take the first steps (on your own machine)

Pick the line for your system. Both tools come from the same project.

brew install kubectx                                   # macOS and Linux with Homebrew: installs both
sudo apt install kubectx                               # Debian and Ubuntu: installs both
kubectl krew install ctx && kubectl krew install ns    # as kubectl plugins: kubectl ctx, kubectl ns
kubectx                        # list contexts; the current one is highlighted
kubectx prod                   # Switched to context "prod".
kubectx -                      # back to the one before
kubens                         # list namespaces in this cluster
kubens kube-system             # Active namespace is "kube-system".
kubectl get pods               # shows kube-system, no -n needed
kubens -                       # back to the previous namespace

Example · The same session with plain kubectl, as in the exam

kubectl config get-contexts
CURRENT   NAME   CLUSTER        AUTHINFO     NAMESPACE
*         dev    dev-cluster    dev-admin    shop
          prod   prod-cluster   prod-admin

The star marks the current context. The last column is its default namespace; empty means default.

kubectl config use-context prod                           # Switched to context "prod".
kubectl config set-context --current --namespace=shop     # Context "prod" modified.
kubectl config view --minify -o jsonpath='{..namespace}'  # shop
kubectl get pods                                          # Pods in shop, on prod
kubectl config set-context --current --namespace=default  # put it back when the task is done

--minify reduces the output to the current context only, which is why the JSONPath finds a single namespace.

Example · Tidy up long context names

Cloud providers generate names such as gke_shop-project_europe-west1-b_prod. Rename them once:

kubectx prod=gke_shop-project_europe-west1-b_prod
# Context "gke_shop-project_europe-west1-b_prod" renamed to "prod".

kubectx prod=.                 # the dot means "the current context"

With kubectl:

kubectl config rename-context gke_shop-project_europe-west1-b_prod prod

Renaming changes only the label in your file. The cluster and the user entries keep their names, and nothing changes on the server. The same is true for deleting: kubectx -d prod removes the context entry and leaves the cluster and user entries in the file.

Example · Build your own two-letter helpers

If you may not install tools on a machine but may edit your shell profile, two functions give you most of the comfort:

kx() { [ -n "$1" ] && kubectl config use-context "$1" || kubectl config get-contexts; }
kn() { [ -n "$1" ] && kubectl config set-context --current --namespace="$1" \
       || kubectl config view --minify -o jsonpath='{..namespace}{"\n"}'; }

kx lists contexts, kx prod switches, kn prints the current namespace and kn shop sets it. In the exam it is quicker to type the full commands, or to press the up arrow, than to write helpers.

Tricks

Common mistakes

  • Relying on the tools in the exam. They are not there. kubectx: command not found in the middle of a task costs time and calm.
  • Forgetting --current. kubectl config set-context --namespace=shop without a context name or --current fails with an error. With a name that does not exist, as in set-context shop --namespace=shop, it silently creates a new, empty context called shop and your namespace does not change.
  • Typing the namespace wrong in set-context. kubectl does not check that the namespace exists. The command succeeds, and later commands return No resources found in shpo namespace or fail with namespaces "shpo" not found.
  • Thinking the switch is per terminal. The change is in the file, so every terminal that uses the same kubeconfig switches too. A second window you believed was on dev is now on prod.
  • Expecting the namespace to follow you across contexts. Each context stores its own. After use-context, check the namespace again.
  • Believing a deleted context removes access. Deleting a context only removes an entry from your file. The credentials stay in the file, and the account and its permissions stay in the cluster.

Recap

  • A context is a cluster, a user and an optional namespace, stored in your kubeconfig.
  • kubectx edits current-context; kubens edits the namespace of the current context. Nothing changes in the cluster.
  • kubens checks that the namespace exists; kubectl config set-context does not.
  • The dash (kubectx -, kubens -) is the one feature with no kubectl equivalent.
  • The exam has neither tool. Use kubectl config get-contexts, use-context <name> and set-context --current --namespace=<name>.
  • Verify the context and the namespace before any command that changes something, and reset the namespace between tasks.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Merge two team logins into your own kubeconfig, then rename contexts, give each a default namespace and switch between them with kubectx and kubens or with plain kubectl config.

    Build · Level 2 · standard · target 15 min

  • A kubeconfig with three contexts stopped working. Find out what is wrong with each one from kubectl's own messages and fix the file.

    Fix · Level 3 · challenge · target 20 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.