如何使用Kubernetes Python客户端连接到Google Kubernetes引擎

3
我正在使用Kubernetes Python客户端来管理本地Kubernetes集群:
from kubernetes import client, config


config = client.Configuration()
config.host = "http://local_master_node:8080"
client.Configuration.set_default(config)
print(client.CoreV1Api().v1.list_node())

一切工作都很顺利,直到我需要使用客户提供的由谷歌拥有该项目的密钥文件连接到谷歌云Kubernetes引擎上的项目时。

{
    "type": "...",
    "project_id": "...",
    "private_key_id": "...",
    "private_key": "...",
    "client_email": "...",
    "client_id": "...",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/..."
}

我正在尝试加载它(可能方法不正确):
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.abspath('credentials.json')
config.load_incluster_config()

但是这段代码会引发异常 kubernetes.config.config_exception.ConfigException: 服务主机/端口未设置。

问题如下:

  1. 如何正确地为 Kubernetes Python 客户端提供 Google 凭据?
  2. 如果我走对了路,那么在哪里可以找到用于 Google Cloud 的主机/端口?

一些代码片段将会很有帮助。

1个回答

9

最终,我自己找到了解决方案。

首先,您需要获取 Kubernetes 配置文件。因此,请转到 Google Cloud Platform 的 Kubernetes Engine 面板。选择要连接的集群,然后按下 连接 按钮。选择 在 Cloud Shell 中运行,并在登录 shell 后键入建议的字符串,例如:

$ gcloud container clusters get-credentials ...

然后你可以在~/.kube文件夹中找到配置文件。将其内容保存到一个yaml文件中,然后将该文件作为参数传递给kubernetes.config.load_kube_config函数:

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.abspath('credentials.json')
config.load_kube_config(os.path.abspath('config.yaml'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接