kubectl: error You must be logged in to the server (Unauthorized)

5/19/2020

I've created a service account for CI purposes and am testing it out. Upon trying any kubectl command, I get the error:

error: You must be logged in to the server (Unauthorized)

Below is my .kube/config file

apiVersion: v1
clusters:
- cluster:
    server: <redacted>
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: bamboo
  name: default
current-context: 'default'
kind: Config
preferences: {}
users:
- name: bamboo
  user:
    token: <redacted>

The service account exists and has a cluster role: edit and cluster role binding attached.

What am I doing wrong?

-- bear
kubernetes

1 Answer

5/19/2020

I reproduce the error if I copy the token directly without decoding. Then applied the following steps to decode and set the token and it is working as expected.

$ TOKENNAME=`kubectl -n <namespace> get serviceaccount/<serviceaccount-name> -o jsonpath='{.secrets[0].name}'` 

$ TOKEN=`kubectl -n <namespace> get secret $TOKENNAME -o jsonpath='{.data.token}'| base64 --decode`

$ kubectl config set-credentials <service-account-name> --token=$TOKEN

So, I think it might be your case.

-- hoque
Source: StackOverflow