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
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
kubectluses when you do not pass-n.
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
devtoprodand the namespace changes with it, to whateverprodhas 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
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).
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
KUBECONFIGis honoured. Both tools read and write the kubeconfig thatkubectlwould use, including a file named in theKUBECONFIGvariable. Support for aKUBECONFIGthat lists several files has differed between versions of the tools, so if you merge files that way, test it once or usekubectl config, which always handles it.- Interactive mode. If the fuzzy finder
fzfis installed, runningkubectxorkubenswith no argument opens a searchable menu instead of printing a list. SetKUBECTX_IGNORE_FZF=1to 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 ctxandkubectl 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--readonlyfor a shell that can only read. Checkkubectx --helpto 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.
| Task | With the tools | With plain kubectl |
|---|---|---|
| List contexts | kubectx | kubectl config get-contexts |
| Show the current context | kubectx -c | kubectl config current-context |
| Switch context | kubectx prod | kubectl config use-context prod |
| Go back to the previous context | kubectx - | No equivalent: run use-context with the old name |
| Rename a context | kubectx new=old | kubectl config rename-context old new |
| Delete a context entry | kubectx -d old | kubectl config delete-context old |
| Clear the current context | kubectx -u | kubectl config unset current-context |
| List namespaces | kubens | kubectl get namespaces |
| Show the current namespace | kubens -c | kubectl config view --minify -o jsonpath='{..namespace}' |
| Switch namespace | kubens shop | kubectl config set-context --current --namespace=shop |
| Go back to the previous namespace | kubens - | 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 foundin the middle of a task costs time and calm. - Forgetting
--current.kubectl config set-context --namespace=shopwithout a context name or--currentfails with an error. With a name that does not exist, as inset-context shop --namespace=shop, it silently creates a new, empty context calledshopand your namespace does not change. - Typing the namespace wrong in
set-context.kubectldoes not check that the namespace exists. The command succeeds, and later commands returnNo resources found in shpo namespaceor fail withnamespaces "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
devis now onprod. - 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.
kubectxeditscurrent-context;kubensedits the namespace of the current context. Nothing changes in the cluster.kubenschecks that the namespace exists;kubectl config set-contextdoes not.- The dash (
kubectx -,kubens -) is the one feature with nokubectlequivalent. - The exam has neither tool. Use
kubectl config get-contexts,use-context <name>andset-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.