AWS EKS 执行 kubectl 时 error: You must be logged in to the server (Unauthorized)

在 AWS 上创建好 EKS 后,想要在本地用  kubectl 来管理 EKS,必须用 aws eks update-kubeconfig 来更新本地的 ~/.kube/config 文件或者 KUBECONFIG 环境变量指向的别的配置文件。

比如说你创建 EKS 的用户在本地 ~/.aws/credentials 中的 profile 是 my-aws-profile, 那么完整的 update-kubeconfig 命令就是
$ aws eks --profile my-aws-profile --region us-east-1 update-kubeconfig --name myeks-cluster
Updated context arn:aws:eks:us-east-1:069762108088:cluster/myeks-cluster in /Users/yanbin/.kube/config
再来执行 kubectl get pods 如果出现错误 error: You must be logged in to the server (Unauthorized),肯定是因为你使用的 awscli 命令比较老(到底有多老呢?在 github 上已经无法追溯了,大概是 1.16.266 之前的)。大约生成的 ~/.kube/config 文件末尾像下面那样
 1......
 2- name: arn:aws:eks:us-east-1:069762108088:cluster/myeks-cluster
 3  user:
 4    exec:
 5      apiVersion: client.authentication.k8s.io/v1alpha1
 6      args:
 7      - token
 8      - -i
 9      - myeks-cluster
10      command: aws-iam-authenticator

获得权限的方式是 aws-iam-authenticator, 而该命令与 aws cli 一样的方式获得访问 AWS  的权限,所以需设置相应的环境变量给 EKS 的 kubectl 命令用。

因此 aws-iam-authenticator 也试图根据 AWS_PROFILEACCESS_KEYAWS_SECRET_ACCESS_KEY 来获得 AWS 访问权限。由于没有设置 AWS_PROFILE=my-aws-profile, 所以 aws-iam-authenticator 报出  error: You must be logged in to the server (Unauthorized) 错误。

所以要以 awscli 同样的方式告诉 aws-iam-authenticator 使用用什么 AWS 用户。比如说创建 EKS 的 profile 是 my-aws-profile,那么在执行 kubectl 之前也要设定默认的 AWS_PROFILE, 命令是
$ export AWS_PROFILE=my-aws-profile
或者用下面等价的方式
$ export ACCESS_KEY=******
$ export AWS_SECRET_ACCESS_KEY=******
如果是新版的 awscli 就不会有这样的问题, 因为在执行 aws eks --profile my-aws-profile --region us-east-1 update-kubeconfig --name myeks-cluster 后,命令中的 profile 和  region 会带入到 ~/.kube/config 文件中去,也就不会出现 error: You must be logged in to the server(Unauthorized)  错误了。生成的 ~/.kube/config 内容后部分是
 1users:
 2- name: arn:aws:eks:us-east-1:069762108088:cluster/myeks-cluster
 3  user:
 4    exec:
 5      apiVersion: client.authentication.k8s.io/v1alpha1
 6      args:
 7      - --region
 8      - us-east-1
 9      - eks
10      - get-token
11      - --cluster-name
12      - myeks-cluster
13      command: aws
14      env:
15      - name: AWS_PROFILE
16        value: my-aws-profile

kubectl 读到 ~/.kube/config 后也就知道去使用 my-aws-profile 去获得 AWS 的访问权限。

另有一种情况是 EKS 可能不是 my-aws-profile 所代表的用户创建的,那么请参考下面的链接来解决。

链接:

  1. How do I provide access to other users and roles after cluster creation in Amazon EKS?
永久链接 https://yanbin.blog/aws-eks-kubectl-error-you-must-be-logged-in-to-the-server-unauthorized/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。