无法从kubernetes python客户端连接GKE自动驾驶集群



我在GKE 上创建了一个自动驾驶集群

我想用Python Kubernetes客户端连接和管理它

我可以获得集群的kubeconfig

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

gcloud容器集群获取凭据

当我尝试连接kubernetes的python客户端库时,我得到以下错误

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')

以下是我的想法。我认为这是一个很好的解决方案,因为它可以防止中间人攻击(使用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"

最新更新