0

我在 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')
4

1 回答 1

1

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

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"
于 2021-06-23T11:19:32.353 回答