Skip to content
LF Cert Trainer

Lesson 77 · Section 7: Security

Lesson 77: KubeConfig: how kubectl knows where to connect and who you are

What a kubeconfig file holds (clusters, users and contexts), how kubectl picks one of each for every command, how several files are merged, and how to build, switch and repair a kubeconfig quickly in the exam. · 18 min read · 4 min video

1/11KubeConfig
0:00 / 3:49

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

Why it exists

The API server speaks HTTPS and trusts nobody by default. To run even kubectl get pods, the client must know four things: the address of the API server, the CA certificate that proves the server is genuine, and a credential of its own, usually a client certificate plus its private key. You saw in the TLS lessons where those files come from. Without any configuration you would have to pass them on every command:

kubectl get pods \
  --server https://10.0.0.10:6443 \
  --certificate-authority /etc/kubernetes/pki/ca.crt \
  --client-certificate admin.crt \
  --client-key admin.key

A kubeconfig file stores those values once, gives them names, and lets you keep several sets side by side: several clusters, several identities, and a quick way to switch between them.

A kubeconfig is a file on the client. It is not a Kubernetes object: there is no kubectl get kubeconfig, nothing is stored in etcd, and you never kubectl apply it. It also grants nothing by itself. It only carries an identity; what that identity may do is decided inside the cluster, by the authorization rules of the next lessons.

What it is

A context joins one cluster and one userclusteruserclusteruserCluster prod10.0.0.10:6443 + CACluster dev10.0.1.10:6443 + CAadmin@prodcurrent-contextjane@devnamespace: shopUser adminclient cert + keyUser janeclient cert + key
A context joins one cluster and one user. The file holds three lists. Clusters say where to connect, users say who you are, and each context is only a named pair of the two, with an optional namespace.

Parts:

  • Cluster prod (10.0.0.10:6443 + CA)
  • Cluster dev (10.0.1.10:6443 + CA)
  • admin@prod (current-context)
  • jane@dev (namespace: shop)
  • User admin (client cert + key)
  • User jane (client cert + key)

Connections:

  • admin@prod to Cluster prod: cluster
  • admin@prod to User admin: user
  • jane@dev to Cluster dev: cluster
  • jane@dev to User jane: user

The file is YAML with kind: Config and three lists.

SectionEach entry holdsAnswers
clustersserver (URL of the API server) and the CA certificate used to verify itWhere do I connect, and how do I know it is the real server?
usersA credential: client certificate and key, a token, or a command that fetches oneWho am I?
contextsThe name of one cluster, the name of one user, and optionally a namespaceWhich pair do I use together?
current-contextThe name of one contextWhich pair do I use when I say nothing?
apiVersion: v1
kind: Config
current-context: admin@prod

clusters:
  - name: prod
    cluster:
      server: https://10.0.0.10:6443
      certificate-authority: /etc/kubernetes/pki/ca.crt
  - name: dev
    cluster:
      server: https://10.0.1.10:6443
      certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t...

contexts:
  - name: admin@prod
    context:
      cluster: prod
      user: admin
  - name: jane@dev
    context:
      cluster: dev
      user: jane
      namespace: shop

users:
  - name: admin
    user:
      client-certificate: /home/me/pki/admin.crt
      client-key: /home/me/pki/admin.key
  - name: jane
    user:
      client-certificate-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t...
      client-key-data: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQ...

Three things in this file surprise people:

  • Names are local labels. prod, admin and admin@prod exist only in this file. The API server never sees them. The name the cluster knows you by comes from the credential itself: for a client certificate, the common name (CN) is your user name and the organisations (O) are your groups. A user entry called admin whose certificate says CN=jane is Jane.
  • A context contains no data, only references. The strings under cluster: and user: must match a name in the other lists exactly. A context called admin@prod is a convention, not a rule; banana works as well.
  • Users are not tied to clusters. Nothing in a user entry says which cluster it belongs to. Only a context makes the connection, and a context that pairs Jane's dev certificate with the prod cluster is valid YAML that the prod cluster will reject.

Path or data: two ways to store a certificate

Every certificate field exists in two forms, and you use one of them, not both.

Field with a pathField with inline dataContent of the inline form
certificate-authoritycertificate-authority-dataThe whole PEM file, base64 encoded on one line
client-certificateclient-certificate-dataThe same, for your certificate
client-keyclient-key-dataThe same, for your private key

A path keeps the file short, but the kubeconfig then only works where those files exist. Inline data makes the file self-contained: you can copy that one file to another machine and it works. The files kubeadm writes use inline data for exactly that reason.

base64 -w 0 ca.crt                                  # produce the value for certificate-authority-data
echo "LS0tLS1CRUdJTi..." | base64 -d | openssl x509 -noout -subject -enddate   # read an inline certificate

How it works

What kubectl does with the file on every commandreadscurrentclusteruserverify serverprove identitykubectl get podsno flagskubeconfig~/.kube/configContextadmin@prodCluster entryserver, CA certUser entryclient cert, keyAPI serverauthenticates you
What kubectl does with the file on every command. kubectl reads the file again for each command. The context only points; the cluster entry and the user entry carry the data that the TLS connection needs.

Parts:

  • kubectl get pods (no flags)
  • kubeconfig (~/.kube/config)
  • Context (admin@prod)
  • Cluster entry (server, CA cert)
  • User entry (client cert, key)
  • API server (authenticates you)

Connections:

  • kubectl get pods to kubeconfig: reads
  • kubeconfig to Context: current
  • Context to Cluster entry: cluster
  • Context to User entry: user
  • Cluster entry to API server: verify server
  • User entry to API server: prove identity

kubectl has no session and no login. On every command it reads the kubeconfig again and works through the same steps:

  1. Find the file or files to read (next section).
  2. Choose a context: the --context flag if you gave one, otherwise current-context.
  3. From the context, take the cluster name and the user name, and look both up.
  4. Open a TLS connection to server, and verify the server's certificate with the CA from the cluster entry.
  5. Present the credential from the user entry. The API server authenticates it and then checks authorization.
  6. If the command names no namespace, use the context's namespace, or default when the context has none.

Because the file is read each time, an edit takes effect on the next command. Nothing has to be restarted or reloaded.

Which file kubectl reads

Which file kubectl readsfirst choiceelseelsecontext--kubeconfigone file, no mergeKUBECONFIGlist of files, merged~/.kube/configthe defaultEffective configkubectl config viewCluster + userfor this command
Which file kubectl reads. The flag wins and is never merged. Without it, the files in KUBECONFIG are merged, first value wins. Without either, kubectl falls back to the file in your home directory.

Parts:

  • --kubeconfig (one file, no merge)
  • KUBECONFIG (list of files, merged)
  • ~/.kube/config (the default)
  • Effective config (kubectl config view)
  • Cluster + user (for this command)

Connections:

  • --kubeconfig to Effective config: first choice
  • KUBECONFIG to Effective config: else
  • ~/.kube/config to Effective config: else
  • Effective config to Cluster + user: context
OrderSourceBehaviour
1--kubeconfig FILE on the commandExactly this file. Nothing is merged, and KUBECONFIG is ignored
2KUBECONFIG environment variableA list of files separated by : (by ; on Windows). They are merged
3$HOME/.kube/configThe default when neither of the above is set

When KUBECONFIG lists several files, kubectl merges them in memory with one rule: the first file to set a value wins. If two files both define a user called admin, only the first definition is used, and the second is dropped whole, not combined field by field. The same holds for current-context: it comes from the first file that sets it. kubectl config view prints the merged result, so it is the place to look when the outcome puzzles you.

On top of the file, single flags override single values for one command: --context, --cluster, --user, --namespace, --server, --certificate-authority, --client-certificate, --client-key and --token.

Under the hood · What happens when there is no kubeconfig at all

With no file, no variable and no flags, kubectl has no server address. Outside a cluster it falls back to the historic default http://localhost:8080, which nothing listens on, and prints the most recognisable error in Kubernetes:

The connection to the server localhost:8080 was refused - did you specify the right host or port?

Whenever you see localhost:8080, kubectl found no usable configuration. Typical causes: you became root with sudo -i and root has no ~/.kube/config, KUBECONFIG points at a file that does not exist, or current-context is empty.

Inside a Pod there is one more fallback. kubectl (like every client library) uses the in-cluster configuration: the ServiceAccount token and CA certificate mounted under /var/run/secrets/kubernetes.io/serviceaccount/, and the API server address from the KUBERNETES_SERVICE_HOST variable. That is why kubectl works in a Pod without any kubeconfig, with the permissions of the Pod's ServiceAccount.

kubeconfig files are not only for people

kubectl is one client among many. Every control plane component that talks to the API server uses a kubeconfig in the same format. On a kubeadm control plane node:

File in /etc/kubernetes/Used byIdentity inside
admin.confYou, as cluster administratorkubernetes-admin, in a group that is bound to cluster-admin
super-admin.confEmergencies onlyGroup system:masters, which bypasses authorization entirely
kubelet.confkubeletsystem:node:<node name>
controller-manager.confkube-controller-managersystem:kube-controller-manager
scheduler.confkube-schedulersystem:kube-scheduler

The familiar step after kubeadm init, cp /etc/kubernetes/admin.conf $HOME/.kube/config, is simply putting an administrator's kubeconfig where kubectl looks by default. And when a scheduler or controller manager cannot reach the API server, its .conf file is one of the first things to read: a wrong server line there breaks the component in the same way it breaks kubectl.

The kinds of credential a user entry can hold

FieldWhat it isWhere you meet it
client-certificate and client-key (or the -data forms)An X.509 client certificate signed by the cluster CAkubeadm clusters, the exam, users created through the Certificates API
tokenA bearer token sent in the Authorization headerServiceAccount tokens, for example from kubectl create token
execA command that kubectl runs to obtain a short-lived credentialManaged clusters: aws eks get-token, gke-gcloud-auth-plugin, kubelogin

A user entry may use only one technique. If it holds two that conflict, kubectl refuses to guess and fails.

Using it

Example · Look around: which contexts do I have, and which is active?

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

AUTHINFO is the user entry. The star marks current-context.

kubectl config current-context          # admin@prod
kubectl config view                     # the whole file; certificate data and keys are hidden
kubectl config view --minify            # only the cluster, user and context in use right now
kubectl config view --raw               # with the secrets shown: handle with care

kubectl config view replaces inline data with DATA+OMITTED and keys with REDACTED, so it is safe on a shared screen. --raw is what you need when the output must be a working file.

Example · Switch context, or use another one for a single command

kubectl config use-context jane@dev     # Switched to context "jane@dev".
kubectl get pods                        # dev cluster, as jane, namespace shop

use-context rewrites current-context in the file. The switch survives closing the terminal, and it also applies to every other terminal that uses the same file. To leave the file alone, override per command:

kubectl --context admin@prod get nodes

To change only the namespace that the current context defaults to:

kubectl config set-context --current --namespace=payments
kubectl config view --minify -o jsonpath='{..namespace}'    # payments

Example · Build a kubeconfig for a new user

Jane's certificate jane.crt has been signed by the cluster CA (see the Certificates API lesson), and you have her key jane.key. Write a separate file for her, so that your own configuration is untouched:

kubectl config set-cluster prod \
  --server=https://10.0.0.10:6443 \
  --certificate-authority=/etc/kubernetes/pki/ca.crt \
  --embed-certs=true \
  --kubeconfig=jane.kubeconfig

kubectl config set-credentials jane \
  --client-certificate=jane.crt \
  --client-key=jane.key \
  --embed-certs=true \
  --kubeconfig=jane.kubeconfig

kubectl config set-context jane@prod \
  --cluster=prod --user=jane --namespace=shop \
  --kubeconfig=jane.kubeconfig

kubectl config use-context jane@prod --kubeconfig=jane.kubeconfig

--embed-certs=true copies the file contents into the -data fields, so jane.kubeconfig is the only file Jane needs. Test it before you hand it over:

kubectl --kubeconfig=jane.kubeconfig auth whoami       # Username: jane
kubectl --kubeconfig=jane.kubeconfig get pods
Error from server (Forbidden): pods is forbidden: User "jane" cannot list resource "pods" in API group ""
in the namespace "shop"

Forbidden here is success. The cluster recognised Jane, so the kubeconfig is correct. She has no permissions yet, and that is fixed with a Role and RoleBinding, not in this file.

On a kubeadm control plane node there is a shortcut that signs a certificate and prints a finished kubeconfig:

kubeadm kubeconfig user --client-name=jane --org=developers > jane.kubeconfig

Example · Repair a kubeconfig that stopped working

The task: "kubectl --kubeconfig /root/dev.kubeconfig get pods fails. Fix the file." Run the command and let the message tell you which entry to open.

The connection to the server controlplane:2379 was refused - did you specify the right host or port?

The address is wrong: 2379 is the etcd port, and the API server listens on 6443. Fix server in the cluster entry, either in an editor or with one command:

kubectl config set-cluster dev --server=https://controlplane:6443 --kubeconfig=/root/dev.kubeconfig

Run it again:

error: unable to read client-cert /etc/kubernetes/pki/users/dev-user/developer-user.crt for dev-user
due to open /etc/kubernetes/pki/users/dev-user/developer-user.crt: no such file or directory

Now a path in the user entry is wrong. List the directory, find the real file name, and correct the path:

ls /etc/kubernetes/pki/users/dev-user/               # dev-user.crt  dev-user.key
kubectl config set-credentials dev-user \
  --client-certificate=/etc/kubernetes/pki/users/dev-user/dev-user.crt \
  --kubeconfig=/root/dev.kubeconfig
kubectl --kubeconfig /root/dev.kubeconfig get pods   # works

Such tasks often hide two faults. Keep running the command until it succeeds, not until the first error is gone.

Example · Work with several files at once, then merge them into one

You received dev.kubeconfig and want its contexts next to your own:

export KUBECONFIG=$HOME/.kube/config:$HOME/dev.kubeconfig
kubectl config get-contexts              # contexts from both files

To make that permanent, write the merged result to a single file. --flatten turns every path into inline data so the result is self-contained:

kubectl config view --flatten > /tmp/merged
cp ~/.kube/config ~/.kube/config.bak
mv /tmp/merged ~/.kube/config
unset KUBECONFIG

Never redirect straight into a file that is also being read (kubectl config view --flatten > ~/.kube/config): the shell empties the file before kubectl reads it.

To hand someone one context out of a large file, combine three flags:

kubectl config view --minify --flatten --context=jane@dev > jane-dev.kubeconfig

What each error means

MessageThe broken partFix
The connection to the server localhost:8080 was refusedNo configuration was found at allCheck KUBECONFIG, ~/.kube/config, the user you are logged in as, and current-context
The connection to the server host:port was refusedCluster entry: wrong server host or port, or the API server is downCompare with --secure-port (6443 by default); if the address is right, check the API server itself
x509: certificate signed by unknown authorityCluster entry: wrong CA certificatePoint certificate-authority at the cluster's ca.crt, or replace the -data value
x509: certificate is valid for ..., not ...Cluster entry: server uses a name or IP that is not in the API server certificateUse a name from the certificate's SANs
unable to read client-cert ... or client-key ...User entry: a path does not existCorrect the path
context "x" does not exist or cluster "x" does not existA name does not match between the listsCompare the names with kubectl config get-contexts and get-clusters
error: You must be logged in to the server (Unauthorized)User entry: the credential is not accepted (wrong CA signed it, or it expired)Check the certificate with openssl x509 -noout -issuer -enddate
Error from server (Forbidden)Nothing in the file. The user is known but has no permissionRole and RoleBinding

Tricks

Common mistakes

  • Expecting the kubeconfig to grant access. It only presents an identity. A perfect file for a user without a RoleBinding gives Forbidden on everything.
  • Thinking the user entry's name is the user name. The cluster reads the name from the certificate's CN or from the token. Renaming the entry changes nothing on the server.
  • Mixing up the path and data fields. certificate-authority takes a path; certificate-authority-data takes base64 text. A path in a -data field gives a base64 or PEM parsing error, and base64 text in a path field gives "no such file".
  • Base64 with line breaks. base64 ca.crt wraps its output on Linux. Use base64 -w 0 so the value is one line.
  • A context that names a cluster or user that is not defined. The spelling must match exactly, including case.
  • Forgetting that use-context is persistent and shared. It changes the file, so another terminal, or a script running in the background, switches cluster with you. Use --context for one-off commands.
  • Setting KUBECONFIG and wondering why --kubeconfig ignores it. The flag reads one file and never merges.
  • Using insecure-skip-tls-verify: true to make an x509 error go away. It works, by no longer checking that you are talking to the real API server. Fix the CA certificate instead.
  • Copying a kubeconfig that uses paths to another machine. The certificates stay behind. Export with kubectl config view --flatten --raw first.

Recap

  • A kubeconfig has three lists: clusters (server and CA), users (credentials) and contexts (one cluster, one user, optional namespace). current-context picks the default.
  • kubectl reads it on every command: --kubeconfig first, else the merged files in KUBECONFIG (first value wins), else ~/.kube/config.
  • Switch with kubectl config use-context, or per command with --context. Set a default namespace with kubectl config set-context --current --namespace=NAME.
  • Build entries with set-cluster, set-credentials and set-context; add --embed-certs=true for a file that works anywhere. Inspect with kubectl config view --minify.
  • The file carries identity, not permission. Read the error: refused means the address, x509 means the CA, unable to read means a path, and Forbidden means the file is fine.

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

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

  • Turn a certificate and a key into one self-contained kubeconfig file that logs a colleague in to the right cluster and namespace.

    Build · Level 2 · standard · target 15 min

  • 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.