This error occurs when the kubectl client does not have the correct certificates to interact with the Kubernetes API Server. Every certificate has an expiry date. Kubernetes has mechanisms to update the certificate automatically.

I was getting the error “You must be logged in to the server (Unauthorized)“. While executing the kubectl command. The command was working perfectly in the cluster before few hours and there was no modifications happened in the cluster.

You can use the following command to check the expiry details of the certificates used internally in the Kubernetes cluster. If the certificates are expired, we need to renew the certificates.

kubeadm alpha certs check-expiration

A sample response is given below.

From the above screenshot, In the above screenshot certificates will expire in 6 hours. If you see an expiry of the certificates, you can renew the certificates by issuing the following command.

Note: Take the back up of all the old certs and config file as a safety precaution

kubeadm alpha certs renew all

The sample response while executing the above command is given below.

Now you can check the expiry date of the certificates and verify whether everything got updated.

kubeadm alpha certs check-expiration

Also execute some kubectl command to ensure that the kubectl got the right config file to interact with the cluster.

Sample commands are given below.

kubectl get pods --all-namespaces

kubectl get nodes

If you are again getting the error You must be logged in to the server (Unauthorized), try the following hack.

Login to the master node, copy the config file /etc/kubernetes/admin.conf and paste it in the location $HOME/.kube/config.

The command is given below.

cp /etc/kubernetes/admin.conf $HOME/.kube/config

After doing this, try executing kubectl commands. You can copy this config file to any node where you have kubectl

Advertisement