使用 Python 为 Google Kubernetes Engine (GKE) 构建 Kubernetes 客户端

使用 python 为 google kubernetes engine (gke) 构建 kubernetes 客户端

这篇博文介绍了一种使用 python 为 gke 创建 kubernetes 客户端的有效方法。通过利用 google-cloud-container、google-auth 和 kubernetes 库,无论您的应用程序是在本地运行还是在 google cloud 上运行,您都可以使用相同的代码与 kubernetes api 进行交互。这种灵活性来自于使用应用程序默认凭证(adc)来验证和动态构建 kubernetes api 交互所需的请求,从而无需使用额外的工具或配置文件(如 kubeconfig)。

本地运行时,常见的方法是使用 gcloud 容器集群 get-credentials 命令生成 kubeconfig 文件并使用 kubectl 与 kubernetes api 交互。虽然此工作流程对于本地设置来说是自然且有效的,但在 cloud run 或其他 google cloud 服务等环境中却变得不太实用。

借助 adc,您可以通过动态配置 kubernetes 客户端来简化对 gke 集群的 kubernetes api 的访问。这种方法可确保以一致、高效的方式连接到集群,而无需管理外部配置文件或安装额外工具的开销。

先决条件

1. 使用 google cloud 进行身份验证

如果您在本地运行代码,只需使用以下命令进行身份验证:

gcloud auth application-default login

这将使用您的用户帐户凭据作为应用程序默认凭据(adc)。

立即学习“Python免费学习笔记(深入)”;

如果您在 cloud run 等 google cloud 服务上运行代码,则无需手动处理身份验证。只需确保该服务具有正确配置的服务帐户,并具有访问 gke 集群所需的权限。

2. 收集您的集群详细信息

运行脚本之前,请确保您了解以下详细信息:

google cloud 项目 id:托管 gke 集群的项目的 id。集群位置:集群所在的区域或可用区(例如 us-central1-a)。集群名称:您要连接的 kubernetes 集群的名称。

脚本

下面是为 gke 集群设置 kubernetes 客户端的 python 函数。

from google.cloud import container_v1import google.authimport google.auth.transport.requestsfrom kubernetes import client as kubernetes_clientfrom tempfile import namedtemporaryfileimport base64import yamldef get_k8s_client(project_id: str, location: str, cluster_id: str) -> kubernetes_client.corev1api:    """    fetches a kubernetes client for the specified gcp project, location, and cluster id.    args:        project_id (str): google cloud project id        location (str): location of the cluster (e.g., "us-central1-a")        cluster_id (str): name of the kubernetes cluster    returns:        kubernetes_client.corev1api: kubernetes corev1 api client    """    # retrieve cluster information    gke_cluster = container_v1.clustermanagerclient().get_cluster(request={        "name": f"projects/{project_id}/locations/{location}/clusters/{cluster_id}"    })    # obtain google authentication credentials    creds, _ = google.auth.default()    auth_req = google.auth.transport.requests.request()    # refresh the token    creds.refresh(auth_req)    # initialize the kubernetes client configuration object    configuration = kubernetes_client.configuration()    # set the cluster endpoint    configuration.host = f'https://{gke_cluster.endpoint}'    # write the cluster ca certificate to a temporary file    with namedtemporaryfile(delete=false) as ca_cert:        ca_cert.write(base64.b64decode(gke_cluster.master_auth.cluster_ca_certificate))        configuration.ssl_ca_cert = ca_cert.name    # set the authentication token    configuration.api_key_prefix['authorization'] = 'bearer'    configuration.api_key['authorization'] = creds.token    # create and return the kubernetes corev1 api client    return kubernetes_client.corev1api(kubernetes_client.apiclient(configuration))def main():    project_id = "your-project-id"  # google cloud project id    location = "your-cluster-location"  # cluster region (e.g., "us-central1-a")    cluster_id = "your-cluster-id"  # cluster name    # retrieve the kubernetes client    core_v1_api = get_k8s_client(project_id, location, cluster_id)    # fetch the kube-system namespace    namespace = core_v1_api.read_namespace(name="kube-system")    # output the namespace resource in yaml format    yaml_output = yaml.dump(namespace.to_dict(), default_flow_style=false)    print(yaml_output)if __name__ == "__main__":    main()

它是如何运作的

1. 连接gke集群

get_k8s_client 函数首先使用 google-cloud-container 库从 gke 获取集群详细信息。该库与 gke 服务交互,允许您检索集群的 api 端点和证书颁发机构 (ca) 等信息。这些详细信息对于配置 kubernetes 客户端至关重要。

gke_cluster = container_v1.clustermanagerclient().get_cluster(request={    "name": f"projects/{project_id}/locations/{location}/clusters/{cluster_id}"})

需要注意的是,google-cloud-container 库是为与 gke 作为服务交互而设计的,而不是直接与 kubernetes api 交互。例如,虽然您可以使用此库检索集群信息、升级集群或配置维护策略(类似于使用 gcloud 容器集群命令执行的操作),但您无法使用它直接获取 kubernetes api 客户端。这种区别就是为什么该函数在从 gke 获取必要的集群详细信息后单独构建 kubernetes 客户端。

2. 使用 google cloud 进行身份验证

为了与 gke 和 kubernetes api 交互,该函数使用 google cloud 的应用程序默认凭据 (adc) 进行身份验证。以下是身份验证过程的每个步骤的工作原理:

google.auth.default()

此函数检索代码运行环境的 adc。根据上下文,它可能会返回:

用户帐户凭据(例如,来自本地开发设置中的 gcloud auth 应用程序默认登录)。服务帐户凭据(例如,在 cloud run 等 google cloud 环境中运行时)。

它还会返回关联的项目 id(如果可用),尽管在本例中仅使用凭据。

google.auth.transport.requests.request()

这将创建一个 http 请求对象,用于处理与身份验证相关的网络请求。它在内部使用 python 的 requests 库,并提供标准化的方法来刷新凭据或请求访问令牌。

creds.refresh(auth_req)

当使用 google.auth.default() 检索 adc 时,凭证对象最初不包含访问令牌(至少在本地环境中)。 fresh() 方法显式获取访问令牌并将其附加到凭证对象,使其能够对 api 请求进行身份验证。

以下代码演示了如何验证此行为:

# obtain google authentication credentialscreds, _ = google.auth.default()auth_req = google.auth.transport.requests.request()# inspect credentials before refreshingprint(f"access token (before refresh()): {creds.token}")print(f"token expiry (before refresh()): {creds.expiry}")# refresh the tokencreds.refresh(auth_req)# inspect credentials after refreshingprint(f"access token (after): {creds.token}")print(f"token expiry (after): {creds.expiry}")

示例输出:

access token (before refresh()): nonetoken expiry (before refresh()): 2024-11-24 06:11:19.640651access token (after): **********token expiry (after): 2024-11-24 07:16:06.866467

调用refresh()之前,token属性为none。调用刷新()后,凭证将填充有效的访问令牌及其到期时间。

3.配置kubernetes客户端

kubernetes 客户端是使用集群的 api 端点、ca 证书的临时文件和刷新的承载令牌进行配置的。这确保客户端可以安全地进行身份验证并与集群通信。

configuration.host = f'https://{gke_cluster.endpoint}'configuration.api_key['authorization'] = creds.token

ca 证书临时存储并由客户端引用以进行安全 ssl 通信。通过这些设置,kubernetes 客户端已完全配置并准备好与集群交互。

示例输出

这是 kube-system 命名空间的 yaml 输出示例:

api_version: v1kind: Namespacemetadata:  annotations: null  creation_timestamp: 2024-11-24 04:49:48+00:00  deletion_grace_period_seconds: null  deletion_timestamp: null  finalizers: null  generate_name: null  generation: null  labels:    kubernetes.io/metadata.name: kube-system  managed_fields:  - api_version: v1    fields_type: FieldsV1    fields_v1:      f:metadata:        f:labels:          .: {}          f:kubernetes.io/metadata.name: {}    manager: kube-apiserver    operation: Update    subresource: null    time: 2024-11-24 04:49:48+00:00  name: kube-system  namespace: null  owner_references: null  resource_version: '15'  self_link: null  uid: 01132228-7e86-4b74-8b78-8ceaa8df9913spec:  finalizers:  - kubernetesstatus:  conditions: null  phase: Active

结论

这种方法强调了使用相同代码与 kubernetes api 交互的可移植性,无论是在本地运行还是在 cloud run 等 google cloud 服务上运行。通过利用应用程序默认凭证 (adc),我们演示了一种灵活的方法来动态生成 kubernetes api 客户端,而无需依赖预先生成的配置文件或外部工具。这使得构建能够无缝适应不同环境的应用程序变得容易,从而简化了开发和部署工作流程。

以上就是使用 Python 为 Google Kubernetes Engine (GKE) 构建 Kubernetes 客户端的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1354300.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
如何在 Google Colab 上运行 Samurai
上一篇 2025年12月13日 18:26:08
有关如何有效提示 Amazon Q 的提示
下一篇 2025年12月13日 18:26:20

相关推荐

发表回复

登录后才能评论
关注微信