首页 > 解决方案 > 在运行 AppEngine 服务中执行 gcloud

问题描述

正在运行的 App Engine 网络应用程序中gcloud获得可用的推荐方法是什么?

背景:
Kubernetes Python 客户端用于subprocess执行gcloud(取自cmd-path配置~/.kube/config)以刷新访问令牌。由于 Web 应用程序使用kubernetespython 库与集群交互,因此该gcloud命令必须在 App Engine 服务中可用。因此,这与在 cloudbuild 或其他 CI 步骤期间运行无关,而是在 App Engine 服务内部gcloud进行访问。gcloud

可能的解决方案:
在 Cloud Build 期间,当然可以执行Linux 的 gcloud install 指令以使该工具在应用程序目录中可用,但有更好的解决方案吗?

谢谢!

标签: pythongoogle-app-enginekubernetesgoogle-cloud-platformgcloud

解决方案


IIUC Kubernetes 的 Python 客户端需要一个 Kubernetes 配置,您正在使用gcloud container clusters get-credentials它来自动创建配置;Kubernetes 的 Python 客户端不需要gcloud.

我推荐一种不同的方法,使用 Google 的 GKE API 客户端库(容器)以编程方式创建 Kubernetes 配置,Kubernetes Python 客户端可以从 App Engine 中使用该配置。您需要确保 App Engine 应用所使用的服务帐户具有足够的权限。

不幸的是,我没有使用 Kubernetes Python 客户端完成此操作,但我正在使用 Kubernetes Golang 客户端执行此操作。

方法是使用 Google 的 Container API 来获取 GKE 集群的详细信息。

API 资源管理器:clusters.get

Python API 客户端库:cluster.get

从响应 ( Cluster ) 中,您可以创建创建 Kubernetes 客户端可接受的 Kubernetes 配置所需的一切。

以下是 Golang 代码的摘要:

ctx := context.Background()
containerService, _ := container.NewService(ctx)

name := fmt.Sprintf(
    "projects/%s/locations/%s/clusters/%s",
    clusterProject,
    clusterLocation,
    clusterName,
)

rqst := containerService.Projects.Locations.Clusters.Get(name)
resp, _ := rqst.Do()

cert, _ := base64.StdEncoding.DecodeString(resp.MasterAuth.ClusterCaCertificate)

server := fmt.Sprintf("https://%s", resp.Endpoint)

apiConfig := api.Config{
    APIVersion: "v1",
    Kind:       "Config",
    Clusters: map[string]*api.Cluster{
        clusterName: {
            CertificateAuthorityData: cert,
            Server:                   server,
        },
    },
    Contexts: map[string]*api.Context{
        clusterName: {
            Cluster:  clusterName,
            AuthInfo: clusterName,
        },
    },
    AuthInfos: map[string]*api.AuthInfo{
        clusterName: {
            AuthProvider: &api.AuthProviderConfig{
                Name: "gcp",
                Config: map[string]string{
                    "scopes": "https://www.googleapis.com/auth/cloud-platform",
                },
            },
        },
    },
}

推荐阅读