使用模拟获取 GKE 集群凭据后无法执行 运行 'kubectl' 命令

Unable to run 'kubectl' commands after using impersonation to fetch GKE cluster credentials

我的Objective

我想使用 GCP 模拟来获取我的 GKE 集群凭据。然后我想 运行 kubectl 命令。

初始上下文

  1. 我有一个名为 rakib-example-project
  2. 的 GCP 项目
  3. 我在名为的项目中有 2 个 ServiceAccounts:
    • owner@rakib-example-project.iam.gserviceaccount.com
      • 它具有项目范围的 roles/owner 角色 - 因此它可以在 GCP 项目中做任何事情
    • executor@rakib-example-project.iam.gserviceaccount.com
      • 它只有项目范围的 roles/iam.serviceAccountTokenCreator 角色 - 因此它可以 模拟 GCP 项目中的 owner ServiceAccount
  4. 我在名为 my-gke-cluster
  5. 的项目中有 1 个 GKE 集群

问题

✅ 我已经认证为 执行者 ServiceAccount:

$ gcloud auth activate-service-account --key-file=my_executor_sa_key.json

Activated service account credentials for: [executor@rakib-example-project.iam.gserviceaccount.com]

✅ 我通过模拟 owner:

获取了 GKE 集群凭证
$ gcloud container clusters get-credentials my-gke-cluster \
  --zone asia-southeast1-a \
  --project rakib-example-project \
  --impersonate-service-account=owner@rakib-example-project.iam.gserviceaccount.com

WARNING: This command is using service account impersonation. All API calls will be executed as [owner@rakib-example-project.iam.gserviceaccount.com].
WARNING: This command is using service account impersonation. All API calls will be executed as [owner@rakib-example-project.iam.gserviceaccount.com].
Fetching cluster endpoint and auth data.
kubeconfig entry generated for my-gke-cluster.

❌ 由于缺少 container.nodes.list 权限,我无法列出集群节点:

$ kubectl get nodes

Error from server (Forbidden): nodes is forbidden: User "executor@rakib-example-project.iam.gserviceaccount.com" cannot list resource "nodes" in API group "" at the cluster scope: requires one of ["container.nodes.list"] permission(s).

但我已经模拟了 Owner ServiceAccount。为什么它仍然缺少权限?

我的局限性

如果我将 executor ServiceAccount 授予 roles/container.admin 角色,效果会很好。但是,由于合规性要求,我不能将此类角色授予我的 executor ServiceAccount。我只能模拟 owner ServiceAccount,然后通过它做任何我想做的事——不能直接做。

如果你在这个位置查看你的 kubeconfig 文件 ~/.kube/config,你可以看到授权列表和秘密,例如

- name: gke_gdglyon-cloudrun_us-central1-c_knative
  user:
    auth-provider:
      config:
        access-token: ya29.<secret>-9XQmaTQodj4kS39w
        cmd-args: config config-helper --format=json
        cmd-path: /usr/lib/google-cloud-sdk/bin/gcloud
        expiry: "2020-08-25T17:48:39Z"
        expiry-key: '{.credential.token_expiry}'
        token-key: '{.credential.access_token}'
      name: gcp

您看到外部引用(expiry-keytoken-key)和一个 cmd-path。命令路径很有趣,因为当需要生成新的令牌时,它会被调用。

但是,您会看到任何关于假冒的提及。您必须将其添加到命令路径中,默认情况下使用。为此,将其添加到您的配置中,如下所示:

gcloud config set auth/impersonate_service_account owner@rakib-example-project.iam.gserviceaccount.com

现在,每次使用 gcloud CLI 都会使用模拟服务帐户,这就是您想要生成有效的 access_token 以访问您的 GKE 集群