kubectl, kubeconfig and contexts
How kubectl finds a cluster and proves who you are: clusters, users and contexts, merging kubeconfig files, credential plugins, and avoiding the wrong cluster.
kubectl, kubeconfig and contexts
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- kubectl is an HTTP client for the API server. A kubeconfig file tells it where the server is, how to trust it, and which credentials to present.
- A kubeconfig has three lists: clusters (URL and CA), users (credentials), and contexts that pair one cluster with one user and an optional default namespace. current-context picks one.
- kubectl reads --kubeconfig, else every file in $KUBECONFIG merged in order, else ~/.kube/config. In a merge the first file to set a value wins, and use-context writes to the first file.
- Cloud clusters usually store no secret at all. An exec plugin such as aws eks get-token or gke-gcloud-auth-plugin fetches a short-lived token on each call.
- kubectl auth whoami shows who the server thinks you are. Explicit --context flags, prompts that show the context, and separate files for production prevent wrong-cluster accidents.
Many clusters, one command
A working engineer rarely has one cluster. There is a local kind cluster, a shared dev cluster, staging, and production in two regions. Each has a different URL, a different certificate authority and a different way to log in. You still type the same kubectl get pods. Something has to decide, for each command, which cluster it goes to and which identity it carries, and has to make that easy to switch and hard to get wrong.
That something is the kubeconfig file.
kubectl is just an API client
Recall from the API lesson that the API is REST over HTTPS. kubectl turns your command into those requests. To do that it needs three things: the server’s URL, a way to verify the server’s TLS certificate, and credentials to present. A kubeconfig holds all three, organised into lists:
apiVersion: v1
kind: Config
clusters:
- name: lab
cluster:
server: https://127.0.0.1:6441
certificate-authority-data: LS0tLS1CRUdJTi... # base64 CA cert
users:
- name: ci
user:
token: eyJhbGciOiJSUzI1NiIs... # a ServiceAccount token
contexts:
- name: ci@lab
context:
cluster: lab
user: ci
namespace: payments
current-context: ci@lab
- A cluster entry is a server URL plus the CA used to trust it.
- A user entry is a set of credentials: a client certificate and key, a bearer token, or an exec plugin.
- A context names a pairing of one cluster and one user, plus a default namespace.
- current-context is the pairing used when you don’t say otherwise.
Think of it like a keyring with labelled tags. The clusters are the doors, the users are the keys, and each context is a tag that says “this key, this door”.
Building one, and seeing who you are
In the lab, a ServiceAccount called ci was given edit rights in a payments namespace, and a kubeconfig was built for it with kubectl config commands:
kubectl create namespace payments
kubectl create serviceaccount ci -n payments
kubectl create rolebinding ci-edit -n payments --clusterrole=edit --serviceaccount=payments:ci
TOKEN=$(kubectl create token ci -n payments --duration=1h)
export KUBECONFIG=ci.kubeconfig
kubectl config set-cluster lab --server=https://127.0.0.1:6441 \
--certificate-authority=ca.crt --embed-certs
kubectl config set-credentials ci --token="$TOKEN"
kubectl config set-context ci@lab --cluster=lab --user=ci --namespace=payments
kubectl auth whoami then asks the API server who it thinks you are, which is the only answer that matters:
$ kubectl --context ci@lab auth whoami
ATTRIBUTE VALUE
Username system:serviceaccount:payments:ci
Groups [system:serviceaccounts system:serviceaccounts:payments system:authenticated]
$ kubectl --context ci@lab get pods
No resources found in payments namespace.
$ kubectl --context ci@lab get pods -n default
Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:payments:ci"
cannot list resource "pods" in API group "" in the namespace "default"
(Output trimmed to the main rows.) The context’s namespace: payments only set the default; the Forbidden came from RBAC. A namespace in a context is a convenience, never a boundary. RBAC and authentication cover the server side.
Where kubectl looks, and how files merge
The precedence, from the kubeconfig docs:
--kubeconfig pathon the command line, which uses exactly that file.- Otherwise
$KUBECONFIG, a colon-separated list (semicolons on Windows) of files that are merged. - Otherwise
~/.kube/config.
Merging lets you keep one file per cluster and combine them:
$ KUBECONFIG=admin.kubeconfig:ci.kubeconfig kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
ci@lab lab ci payments
* lab-A lab-A admin
Two merge rules matter. When two files define the same entry or current-context, the first file wins. And commands that modify the config write to the first file too. After kubectl config use-context ci@lab with that KUBECONFIG, the lab showed current-context: ci@lab written into admin.kubeconfig, while ci.kubeconfig, where the context lives, still had an empty current-context.
kubectl config view --minify prints only what the current context uses, which is the quickest way to answer “what am I connected to?”. Add --raw if you need the embedded certificates, and be careful where that output goes.
Credentials that are not in the file
Static credentials in a kubeconfig, a client key or a long-lived token, are a liability. Copy the file and you have copied the identity. Client certificates are worst: the API server cannot revoke one before it expires.
Managed clusters avoid storing secrets with exec credential plugins. The user entry names a command, and kubectl runs it to get a short-lived token on demand:
users:
- name: eks-prod
user:
exec:
apiVersion: client.authentication.k8s.io/v1beta1
command: aws
args: [eks, get-token, --cluster-name, prod]
GKE uses gke-gcloud-auth-plugin, AKS uses kubelogin, and generic OIDC setups often use the kubectl oidc-login plugin. The kubeconfig then holds no secret at all, only instructions for getting one from your cloud identity.
Not running on the wrong cluster
The classic accident is kubectl delete in production while you thought you were in dev. Some habits that help:
- Pass
--contextexplicitly in scripts and runbooks rather than relying oncurrent-context. - Show the current context in your shell prompt (
kube-ps1and similar), or usekubectx/kubensto switch deliberately. - Keep production credentials in a separate file you only add to
KUBECONFIGwhen you mean it, ideally with a read-only user by default. - Use kuberc, kubectl’s user preferences file (
~/.kube/kuberc, APIkubectl.config.k8s.io/v1beta1), to set safer defaults. With this in the file, everykubectl deleteasks first:
apiVersion: kubectl.config.k8s.io/v1beta1
kind: Preference
defaults:
- command: delete
options:
- name: interactive
default: "true"
$ echo n | kubectl --kuberc kuberc delete cm app-config
You are about to delete the following 1 resource(s):
configmap/app-config
Do you want to continue? (y/N): deletion is cancelled
kuberc is kept separate from kubeconfig on purpose: kubeconfig says where and who, kuberc says how you like kubectl to behave, and you can share one without the other.
About the video
The embed is Techworld with Rajendra’s “Demystifying kubeconfig file” (January 2024, 12 minutes). Its description says it takes a detailed look at the kubeconfig kubectl uses, then creates a new cluster entry and adds clusters, users and contexts by hand, which matches the structure section of this lesson. It is aimed at CKA and CKAD candidates and does not cover exec plugins, merge-order surprises or kuberc, which the lesson adds. English was judged from the “English (US) original” audio track. Code with Gauri’s longer 2026 video in deeper also covers the authentication flow and merging multiple files.
What was run: the ServiceAccount kubeconfig, auth whoami, the Forbidden error, the merged get-contexts, the first-file write of use-context, and the kuberc interactive delete all ran against a local v1.37.3 API server with kubectl v1.37.3, on 2026-11-28. The exec plugin example follows the EKS and Kubernetes authentication docs and was not run.
Where this fits
With a context set, the next question is how to change things: imperative commands and declarative apply.
Check yourself
You run export KUBECONFIG=~/.kube/dev:~/.kube/prod and then kubectl config use-context prod-admin. Which file changed?
~/.kube/dev, the first file in the list. kubectl writes current-context to the first file, even though the prod-admin context is defined in the second. Merged kubeconfigs are convenient but this surprises people.
A teammate's kubeconfig contains client-key-data. Why is copying that file to a shared CI runner a problem?
client-key-data is a private key. Anyone with the file can authenticate as that user until the certificate expires, and Kubernetes has no way to revoke a client certificate short of rotating the CA. Use a ServiceAccount token with a short duration, or an exec plugin backed by the CI system's identity.
kubectl get pods returns pods you don't recognise. What two commands tell you where you are and who you are?
kubectl config current-context, or kubectl config view --minify, shows the cluster, user and namespace in use. kubectl auth whoami shows the identity and groups the API server authenticated you as.
What does a context's namespace field do, and what does it not do?
It sets the default namespace for commands that don't pass -n. It grants nothing and restricts nothing: RBAC decides what you can reach, and -n or -A still go anywhere you have permission.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.