【问题标题】:Unable to connect GKE autopilot cluster from kubernetes python client无法从 kubernetes python 客户端连接 GKE 自动驾驶集群
【发布时间】:2021-08-17 12:30:33
【问题描述】:

我在 GKE 上创建了一个 Autopilot 集群

我想用Python Kubernetes Client连接和管理它

我可以得到集群的kubeconfig

我可以使用命令在本地系统上使用 kubectl 访问集群

gcloud 容器集群获取凭据

当我尝试连接 kubernetes 的 python-client-library 时,出现以下错误

  File "lib/python3.7/site-packages/urllib3/util/retry.py", line 399, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='xxx.xx.xxx.xxx', port=443): Max 
retries exceeded with url: /apis/extensions/v1beta1/namespaces/default/ingresses (Caused by 
SSLError(SSLError(136, '[X509] no certificate or crl found (_ssl.c:4140)')))

这是我正在使用的代码

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "863924b908c7.json"

credentials, project = google.auth.default(
    scopes=['https://www.googleapis.com/auth/cloud-platform', ])

credentials.refresh(google.auth.transport.requests.Request())

cluster_manager = ClusterManagerClient(credentials=credentials)
# cluster = cluster_manager.get_cluster(project)
config.load_kube_config('config.yaml')

【问题讨论】:

  • 你能分享更多你的代码吗?
  • 添加了代码...

标签: python kubernetes google-cloud-platform google-kubernetes-engine kubernetes-python-client


【解决方案1】:

这就是我想出来的。我认为这是一个很好的解决方案,因为它可以防止中间人攻击(使用 SSL),这与野外的其他 python sn-ps 不同。

from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client
from tempfile import NamedTemporaryFile
import base64
import google.auth

credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform',])
credentials.refresh(google.auth.transport.requests.Request())
cluster_manager = ClusterManagerClient(credentials=credentials)
cluster = cluster_manager.get_cluster(name=f"projects/{gcp_project_id}/locations/{cluster_zone_or_region}/clusters/{cluster_id}")

with NamedTemporaryFile(delete=False) as ca_cert:
 ca_cert.write(base64.b64decode(cluster.master_auth.cluster_ca_certificate))

config = client.Configuration()
config.host = f'https://{cluster.endpoint}:443'
config.verify_ssl = True
config.api_key = {"authorization": "Bearer " + credentials.token}
config.username = credentials._service_account_email
config.ssl_ca_cert = ca_cert.name
client.Configuration.set_default(config)

# make calls with client

在 GKE 上,SSL 验证会自动在 IP 上运行。如果您处于由于某种原因无法正常工作的环境中,您可以将 IP 绑定到主机名列表:

from python_hosts.hosts import (Hosts, HostsEntry)
hosts = Hosts()
hosts.add([HostsEntry(entry_type='ipv4', address=cluster.endpoint, names=['kubernetes'])])
hosts.write()
config.host = "https://kubernetes"

【讨论】:

    猜你喜欢
    • 2022-06-23
    • 1970-01-01
    • 2021-06-12
    • 2021-12-23
    • 2020-02-03
    • 2022-11-03
    • 2018-04-12
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多