使用Application Default Credentials访问GKE集群遇认证插件错误求解决方案
解决GKE认证插件移除错误的方案
问题原因
Kubernetes client-go已移除原有的gcp认证插件,必须改用Google官方提供的gke-gcloud-auth-plugin凭证插件完成GKE集群身份验证。
解决步骤
1. 安装认证插件
通过gcloud CLI安装gke-gcloud-auth-plugin:
gcloud components install gke-gcloud-auth-plugin
2. 配置环境变量
设置环境变量,告知client-go使用新插件:
export USE_GKE_GCLOUD_AUTH_PLUGIN=True
若需永久生效,可将该变量添加至shell配置文件(如~/.bashrc或~/.zshrc)。
3. 修改代码中的认证配置
将原代码中AuthProvider类型的认证配置替换为Exec类型,对应新插件。修改getK8sClusterConfigs函数内的AuthInfos部分:
原代码片段:
ret.AuthInfos[name] = &api.AuthInfo{ AuthProvider: &api.AuthProviderConfig{ Name: "gcp", Config: map[string]string{ "scopes": "https://www.googleapis.com/auth/cloud-platform", }, }, }
替换为:
ret.AuthInfos[name] = &api.AuthInfo{ Exec: &api.ExecConfig{ Command: "gke-gcloud-auth-plugin", Args: []string{ "token", "--use_application_default_credentials", "--project", projectId, "--cluster", f.Name, "--location", f.Zone, }, APIVersion: "client.authentication.k8s.io/v1beta1", }, }
4. 确认Application Default Credentials(ADC)配置
若未配置ADC,执行以下命令完成配置:
gcloud auth application-default login
在GCP托管环境(如GCE实例、GKE Pod、Cloud Functions)中运行时,ADC会自动获取服务账号凭证,无需手动配置。
5. 验证代码运行
修改完成后,重新运行代码:
go run main.go -projectId=<你的项目ID>
额外提示
- 确保gcloud CLI为最新版本,可执行
gcloud components update更新 - 若使用较高版本的Kubernetes client-go,可将
ExecConfig的APIVersion改为client.authentication.k8s.io/v1
内容的提问来源于stack exchange,提问作者Uday Chauhan
相关产品推荐
相关产品推荐

