首页 > 解决方案 > 设置 CLOUDSDK_CONFIG 时无法使用 go 客户端访问 Kubernetes 集群

问题描述

我在 GKE 上有一个 Kubernetes 集群。即使在正确设置了 KUBECONFIG="/tmp/kubeconfigxvz" 之后,当我执行kubectl get pods命令时也会失败并出现以下错误

bash-4.3# kubectl get pods
Unable to connect to the server: error executing access token command 
"/google-cloud-sdk/bin/gcloud config config-helper --format=json": err=exit 
status 1 output= stderr=ERROR: (gcloud.config.config-helper) You do not 
currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials, or if you have already logged in with a
different account:

  $ gcloud config set account ACCOUNT

to select an already authenticated account to use.

当我设置CLOUDSDK_CONFIG=/tmp/customdir命令开始工作。

go 客户端如何实现相同的目标?

=== 更新 ===

创建 go 客户端时,我将正确的文件指针传递 clientcmd.BuildConfigFromFlags("", *tmpKubeConfigFile)tmpKubeConfigFile指向/tmp/kubeconfigxvz. 但我认为这还不够,go-client 还需要来自CLOUDSDK_CONFIG目录的更多信息,我认为它需要会话信息或凭据或其他东西。

创建 go-client 时是否也可以传递此 CLOUDSDK_CONFIG ?

BuildConfigFromFlags它接受指向 kubeconfig 文件的指针的输入并返回一个config对象,该对象可以传递给kubernetes.NewForConfig(config)创建客户端的对象。是否有可能或是否存在类似的功能来传递 CLOUDSDK_CONFIG 并返回 go-client 或创建配置?

标签: kuberneteskubernetes-go-client

解决方案


您基本上需要创建一个~/.kube/config文件来直接访问您的 GKE 集群。

您可以在这个 go 客户端示例中看到它正在从中获取配置~/.kube/config

GKE 配置看起来像这样:

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: [REDACTED]
    server: https://x.x.x.x
  name: gke_project_us-central1-a_your-first-cluster-1
contexts:
- context:
    cluster: gke_project_us-central1-a_your-first-cluster-1
    user: gke_project_us-central1-a_your-first-cluster-1
  name: gke_project_us-central1-a_your-first-cluster-1
current-context: gke_project_us-central1-a_your-first-cluster-1
kind: Config
preferences: {}
users:
- name: gke_project_us-central1-a_your-first-cluster-1
  user:
    auth-provider:
      config:
        cmd-args: config config-helper --format=json
        cmd-path: /google/google-cloud-sdk/bin/gcloud
        expiry-key: '{.credential.token_expiry}'
        token-key: '{.credential.access_token}'
      name: gcp

您必须使用以下内容更改用户部分:

- name: myuser
  user:
     token: [REDACTED]

用户是具有令牌的服务帐户,如果您想添加此用户来管理集群中的所有内容,您可以ClusterRoleBind将其添加到admin角色中。

有关RBAC, ServiceAccounts, Roles,的更多信息ClusterRolesUsers您可以在此处查看

顺便说一句,不幸的是,GKE 不允许您访问主节点,因此您无法创建证书身份验证,因为您无权访问该CA.key文件。


推荐阅读