使用服务帐号访问 GKE 中的 Kubernetes API

Kar*_*hik 2 kubernetes google-kubernetes-engine

我的 Kubernetes 集群在 GKE 中运行,我想在集群外运行一个应用程序并与 Kubernetes API 对话。

通过使用从运行中检索到的密码:

gcloud container clusters get-credentials cluster-2 --log-http
Run Code Online (Sandbox Code Playgroud)

我可以使用基本身份验证访问 API。但是我想创建多个 Kubernetes 服务帐户并使用所需的授权配置它们并适当地使用。

因此,我创建了服务帐户并使用以下方法获取了令牌:

kubectl create serviceaccount sauser1
kubectl get serviceaccounts sauser1 -o yaml
kubectl get secret sauser1-token-<random-string-as-retrieved-from-previous-command> -o yaml
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用持有者身份验证获得的令牌访问 Kubernetes API,则会收到 401 HTTP 错误。我认为可能需要为服务帐户设置一些权限,因此根据此处的文档,我创建了以下 YAML 文件:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: pod-reader
subjects:
- kind: ServiceAccount
  name: sauser1
  namespace: default
roleRef:
  kind: ClusterRole
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
Run Code Online (Sandbox Code Playgroud)

并尝试使用以下命令应用它:

kubectl apply -f default-sa-rolebinding.yaml
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

clusterrolebinding "pod-reader" created
Error from server (Forbidden): error when creating "default-sa-rolebinding.yaml"
: clusterroles.rbac.authorization.k8s.io "pod-reader" is forbidden: attempt to g
rant extra privileges: [PolicyRule{Resources:["pods"], APIGroups:[""], Verbs:["g
et"]} PolicyRule{Resources:["pods"], APIGroups:[""], Verbs:["watch"]} PolicyRule
{Resources:["pods"], APIGroups:[""], Verbs:["list"]}] user=&{xyz@gmail.
com  [system:authenticated] map[authenticator:[GKE]]} ownerrules=[PolicyRule{Res
ources:["selfsubjectaccessreviews"], APIGroups:["authorization.k8s.io"], Verbs:[
"create"]} PolicyRule{NonResourceURLs:["/api" "/api/*" "/apis" "/apis/*" "/healt
hz" "/swagger-2.0.0.pb-v1" "/swagger.json" "/swaggerapi" "/swaggerapi/*" "/versi
on"], Verbs:["get"]}] ruleResolutionErrors=[]
Run Code Online (Sandbox Code Playgroud)

我不知道如何从这里开始。我的方法正确还是我在这里遗漏了什么?

更新:根据@JanosLenart 在评论中引用的帖子,修改了 kubectl 命令并且未观察到上述错误。但是访问API,还是报401错误。我使用的 curl 命令是:

curl -k -1 -H "Authorization: Bearer <token>" https://<ip-address>/api/v1/namespaces/default/pods -v
Run Code Online (Sandbox Code Playgroud)

Ahm*_*gle 5

@Janos 指出了潜在问题,但我认为您还需要一个实际的 Cloud IAM 服务帐户,因为您说:

我想在集群外运行一个应用程序 [...]

如果您从外部对 GKE 进行身份验证,我相信您只能使用 Google IAM 身份。(我可能错了,如果是这样,请告诉我。)

在这种情况下,您需要做的是:

  1. 创建一个 IAM 服务帐户并下载它的 json 密钥文件。
  2. 设置GOOGLE_APPLICATION_CREDENTIALS为该文件。
  3. 任何一个:

    • 在您的问题中使用 RBAC 为 IAM 服务帐户的电子邮件地址授予权限

    • 使用 IAM 角色在 GKE API 上提供 IAM 服务帐户(例如Container Developer角色通常就足够了)

  4. kubectl对集群使用命令(确保您.kube/config事先有一个带有集群 IP/CA 证书的文件)和上面的环境变量,它应该可以工作。