如何通过Google Cloud Function调用Python Kubernetes Client在GKE集群中创建Pod?
在Google Cloud Function中通过Python创建GKE Pod的最优方案
首先,你选择Python Kubernetes Client完全没问题,而且其实还有更简洁安全的实现方式——不用手动生成kubeconfig文件,直接借助GCP的服务账号自动获取凭证来连接GKE集群,这比维护kubeconfig要省心得多,也更符合Serverless环境的最佳实践。
核心思路:利用GCP自动服务账号凭证
Cloud Function默认会使用自身的服务账号运行,只要给这个服务账号配置好GKE的权限,就能通过google-auth库自动获取集群访问凭证,无需手动处理kubeconfig。
步骤1:配置Cloud Function服务账号的权限
给你的Cloud Function关联的服务账号(默认是PROJECT_ID@appspot.gserviceaccount.com)添加以下IAM角色:
roles/container.developer:允许创建、管理GKE资源(包括Pod)- 如果你的Pod需要使用特定的服务账号,还需要给这个服务账号添加**
roles/iam.serviceAccountUser**权限,允许它扮演Pod的服务账号
步骤2:编写Python代码实现
首先,确保你的requirements.txt包含必要的依赖:
google-auth>=2.0.0 kubernetes>=26.0.0
然后是核心代码:
from kubernetes import client, config from google.auth.transport.requests import Request import google.auth import os def create_gke_pod(event, context): # 替换成你的集群信息 CLUSTER_NAME = "your-cluster-name" CLUSTER_REGION = "your-cluster-region" PROJECT_ID = os.environ.get("GCP_PROJECT") # 自动获取Cloud Function的服务账号凭证 credentials, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) credentials.refresh(Request()) # 构建Kubernetes客户端配置 configuration = client.Configuration() configuration.host = f"https://container.googleapis.com/v1/projects/{PROJECT_ID}/locations/{CLUSTER_REGION}/clusters/{CLUSTER_NAME}:proxy" configuration.verify_ssl = True configuration.api_key = {"authorization": f"Bearer {credentials.token}"} client.Configuration.set_default(configuration) # 定义要创建的Pod pod_manifest = { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "test-nginx-pod", "namespace": "default" }, "spec": { "containers": [ { "name": "nginx-container", "image": "nginx:latest", "ports": [{"containerPort": 80}] } ] } } # 调用K8s API创建Pod v1 = client.CoreV1Api() try: response = v1.create_namespaced_pod(body=pod_manifest, namespace="default") print(f"Pod创建成功:{response.metadata.name}") return f"Pod {response.metadata.name} 已成功创建" except client.ApiException as e: print(f"创建Pod失败:{e}") return f"创建Pod失败:{e.reason}"
为什么这是更优方案?
- 无需维护kubeconfig:避免了手动生成、存储kubeconfig的麻烦,也不用担心配置过期或泄露
- 安全合规:借助GCP IAM权限控制,比硬编码kubeconfig更安全
- 适配Serverless环境:完全符合Cloud Function无状态、自动凭证的运行模式
如果你一定要用kubeconfig的话(不推荐)
如果因为某些场景必须使用kubeconfig文件,你可以在本地用gcloud container clusters get-credentials生成kubeconfig,然后把kubeconfig的内容作为环境变量(比如KUBECONFIG_CONTENT)注入到Cloud Function中,然后在代码里临时写入文件并加载:
import tempfile from kubernetes import config import os def load_kubeconfig(): kubeconfig_content = os.environ.get("KUBECONFIG_CONTENT") with tempfile.NamedTemporaryFile(mode='w', delete=False) as f: f.write(kubeconfig_content) config.load_kube_config(config_file=f.name)
但这种方式需要定期更新kubeconfig(因为凭证会过期),不如自动凭证方案省心。
内容的提问来源于stack exchange,提问作者Fran Arenas
相关产品推荐
相关产品推荐

