Kubectl error You must be logged in to the server (Unauthorized) when using kubectl

I proceeded with the work referring to the following site (I don't use EKS.I create k8s on ec2 using kops)

Getting Started with kOps on AWS

When I tried to call kubectl get service I got the message: error: You must be logged in to the server (Unauthorized)

Here is what I did:

  1. Setup IAM user(create user and add role)

  2. Cluster State storage(S3)

  3. Prepare local environment

export NAME=myfirstcluster.example.com 
export KOPS_STATE_STORE=s3://prefix-example-com-state-store
  1. Create cluster configuration kops create cluster--zones=us-west-2a${NAME}

  2. Build the Cluster kops update cluster ${NAME} --yes

★success★

  1. When I try to access the cluster e.g. kubectl get nodes, I keep receiving error: You must be logged in to the server (Unauthorized)

Any idea how to fix this issue?

I tried some other way.

  1. attach instance profile to EC2

  2. delete .kube/cache

  3. kubectl apply -f aws-auth.yaml

    apiVersion: v1 kind: ConfigMap metadata: name: aws-auth namespace: kube-system data: mapUsers: | - userarn: arn:aws:iam::xxxx:user/xxx username: xxx groups: - system:masters mapRoles: | - rolearn: arn:aws:iam::xxxx:role/xxx username: system:node:{{EC2PrivateDNSName}} groups: - system:bootstrappers - system:nodes  

Same error: You must be logged in to the server (the server has asked for the client to provide credentials).

  1. Modify .kube/config users:
    name: xxclusterNAMExxx user: exec: apiVersion: client.authentication.k8s.io/v1alpha1 command: aws-iam-authenticator args: - "token" - "-i" - "xxclusterNAMExxx" env: - name: AWS_PROFILE value: "xxxx"

All failed.


Try:

kops export kubecfg --admin 

You can try the following command

$ kops export kubecfg --admin --kubeconfig ~/workspace/kubeconfig --state=s3://YOUR-S3-BUCKET-NAME

https://kops.sigs.k8s.io/releases/1.19-notes/#changes-to-kubernetes-config-export

Yes you need to pass the users as well.

kops export kubecfg --name --admin