kubeconfig and certificates
How kubectl picks a cluster, user and namespace, how to build and switch contexts, how to issue a user certificate with a CertificateSigningRequest, and how to inspect and renew kubeadm certificates.
Exam tasks: 1.1 (manage RBAC: users and credentials), 1.4 (manage the cluster lifecycle: certificates), 5.1 (troubleshoot clusters and nodes)
The decision: which cluster, which identity and which namespace does this command run as, and is the certificate behind that identity still valid?
Every exam task starts with a kubectl config use-context line. Understanding what a kubeconfig holds explains it, and
also explains most "connection refused" and "x509" errors.
What a kubeconfig holds
KUBECONFIG (a colon-separated list) or --kubeconfig override it.clusters, users and contexts, plus the single current-context pointer.etcd subdirectory.expirationSeconds a CertificateSigningRequest can ask for.| Section | Holds | Typical edit |
|---|---|---|
clusters[] | server URL and the CA that signed the API server certificate | Wrong port or address after a rebuild |
users[] | A client certificate and key, a bearer token, or an exec plugin | A new user or an expired credential |
contexts[] | A named triple of cluster, user and namespace | Default namespace for a task |
current-context | The context kubectl uses now | use-context at the start of a task |
Working with contexts
k config get-contexts # all contexts, * marks the current one
k config current-context
k config use-context cka-lab2 # switch cluster and identity
k config set-context --current --namespace=shop # change the default namespace of this context
k config view --minify # only the current context, secrets redacted
k config view --raw --minify # includes the embedded certificate data--namespaceon a single command beats the context's namespace.-Alists every namespace.- Set the namespace on the context for a task that touches one namespace only. It saves typing
-nand avoids creating objects indefaultby mistake. - Several files merge when
KUBECONFIG=a:bis set.k config view --flatten > merged.yamlwrites the result as one file. - On the exam, each task names the context. Run its command every time, even when you think you are already there.
Creating objects in the wrong namespace
A context without a namespace uses default. A task that says "in namespace shop" and an answer created in default
earn nothing, and k get without -n shop will not show your mistake. Check with k get <kind> -A | grep name.
Building a context for a new user
A new human user is a client certificate. Kubernetes has no User object, so the API server trusts the certificate's CN as the username and each O as a group if it was signed by the cluster CA.
Create a key and a certificate request. The -subj sets the identity.
openssl genrsa -out jana.key 2048
openssl req -new -key jana.key -subj "/CN=jana/O=developers" -out jana.csrSubmit it as a CertificateSigningRequest. request is the base64 of the CSR file with no line breaks.
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: jana
spec:
request: <base64 of jana.csr, one line>
signerName: kubernetes.io/kube-apiserver-client
expirationSeconds: 86400
usages: ["client auth"]base64 -w0 jana.csr prints the one-line value on Linux.
Approve it, then read the signed certificate.
k certificate approve jana
k get csr jana -o jsonpath='{.status.certificate}' | base64 -d > jana.crtAdd the credentials and a context, then give the user permissions. A certificate proves who the user is, and RBAC decides what they may do.
k config set-credentials jana --client-certificate=jana.crt --client-key=jana.key --embed-certs=true
k config set-context jana@lab --cluster=<cluster-name> --user=jana --namespace=shop
k create rolebinding jana-view -n shop --clusterrole=view --user=jana
k --context jana@lab auth can-i list pods # yes, once the binding existsExam signal
signerName: kubernetes.io/kube-apiserver-client is for user certificates. kubernetes.io/kubelet-serving and
kubernetes.io/kube-apiserver-client-kubelet are for kubelets. A CSR with the wrong signer or usages is approved but
never issued, and .status.certificate stays empty.
Certificates kubeadm manages
sudo kubeadm certs check-expiration # every cert, its expiry and its CA
sudo kubeadm certs renew all # or one name, such as apiserver
sudo openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -dates -subject -ext subjectAltName| Certificate | File under /etc/kubernetes/pki | Renewed by |
|---|---|---|
| API server serving | apiserver.crt | kubeadm certs renew, or a control plane upgrade |
| API server to kubelet | apiserver-kubelet-client.crt | Same |
| etcd serving, peer, health check | etcd/server.crt, etcd/peer.crt, etcd/healthcheck-client.crt | Same |
| Admin, scheduler, controller manager kubeconfigs | /etc/kubernetes/admin.conf, scheduler.conf, controller-manager.conf (embedded) | Same |
| Kubelet client certificate | /var/lib/kubelet/pki/ | The kubelet rotates it itself |
| Cluster CAs | ca.crt, etcd/ca.crt, front-proxy-ca.crt | Never, unless you replace them by hand |
kubeadm upgrade applyandkubeadm upgrade noderenew leaf certificates unless you pass--certificate-renewal=false, so a cluster that is upgraded once a year never expires.- After renewing, the control plane static Pods still hold the old certificate in memory. Restart them: move each
manifest out of
/etc/kubernetes/manifestsand back, or restart the containers withcrictl. - Copy the new
admin.confto~/.kube/config, because the old embedded client certificate is the one that expired.
Renewing but not restarting
kubeadm certs check-expiration shows new dates after renew all, yet kubectl still says certificate has expired.
The API server process loaded the old file at start. Restart the static Pods.
Errors and what they point to
| What you see | Likely cause |
|---|---|
The connection to the server localhost:8080 was refused | No kubeconfig found. KUBECONFIG is unset and ~/.kube/config is missing |
connection refused to the right address | API server down. Go to the control plane page |
x509: certificate signed by unknown authority | The kubeconfig CA does not match the cluster, for example after a rebuild |
x509: certificate has expired or is not yet valid | An expired client or API server certificate, or a wrong clock |
x509: certificate is valid for X, not Y | The server URL is not in the API server certificate's SANs |
Error from server (Forbidden) | Authentication worked and RBAC denied it. Check bindings |
Unauthorized | Authentication failed: bad token or certificate not signed by the CA |
Scenarios
A context is just a named combination of cluster, user and namespace. Switching to it uses exactly what it names, so a
wrong cluster reference sends every command to production. Fix it with
k config set-context staging --cluster=<staging cluster> --user=stg-admin. kubectl has no cache between runs, and
contexts do select the cluster.
Renewing writes new files, but the running control plane processes still use the certificates they loaded at start, so restart them. kubectl authenticates with the client certificate embedded in the old copy of admin.conf, so copy the renewed file. The CA lasts 10 years and is not involved, workers do not need a reset, and ServiceAccount tokens do not depend on these certificates.
The signer decides what a certificate can be used for. The kubelet-serving signer issues kubelet server certificates and does not sign a user's client certificate. A user needs the kube-apiserver-client signer with the client auth usage. Approving twice or restarting components does not change the signer, and system:masters would grant full access without fixing the request.
Drill
kubectl config use-context cka-lab1
Create a user ravi with a client certificate signed by the cluster, valid for one day. Add the credentials and a
context named ravi@lab1 to the kubeconfig, defaulting to namespace ops. Allow ravi to read Pods in ops only.
Confirm with auth can-i.
openssl genrsa -out ravi.key 2048
openssl req -new -key ravi.key -subj "/CN=ravi" -out ravi.csr
cat <<EOF | k apply -f -
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: ravi
spec:
request: $(base64 -w0 ravi.csr)
signerName: kubernetes.io/kube-apiserver-client
expirationSeconds: 86400
usages: ["client auth"]
EOF
k certificate approve ravi
k get csr ravi -o jsonpath='{.status.certificate}' | base64 -d > ravi.crt
CLUSTER=$(k config view --minify -o jsonpath='{.clusters[0].name}')
k config set-credentials ravi --client-certificate=ravi.crt --client-key=ravi.key --embed-certs=true
k config set-context ravi@lab1 --cluster=$CLUSTER --user=ravi --namespace=ops
k create ns ops --dry-run=client -o yaml | k apply -f -
k create role pod-reader -n ops --verb=get,list,watch --resource=pods
k create rolebinding ravi-reads -n ops --role=pod-reader --user=ravi
k --context ravi@lab1 auth can-i list pods # yes
k --context ravi@lab1 auth can-i list pods -n default # noRelated
- RBAC: the permissions a certificate's identity receives.
- Cluster upgrades: upgrades renew certificates automatically.
- Troubleshooting nodes: kubelet certificate and bootstrap failures.
- kubectl skills:
--context,-nand output flags.
Further reading
RBAC
Roles and ClusterRoles, RoleBindings and ClusterRoleBindings, users, groups and ServiceAccounts as subjects, aggregated ClusterRoles, and proving access with kubectl auth can-i.
Installing a cluster with kubeadm
Preparing nodes (swap, IP forwarding, containerd and the cgroup driver, pkgs.k8s.io packages), kubeadm init and its config file, installing a CNI, joining workers and regenerating join commands.