使用python客户端使用客户端证书进行K8S API访问

时间:2019-09-01 16:39:55

标签: python kubernetes kubernetes-python-client

我的目的是使用python客户端和客户端证书从远程服务器访问我的k8s API,该服务器使用的curl如下所示:

curl --key /XXX/XXX.key --cert /XXX/XXX.crt --cacert /XXX/XXX.crt https://api-k8s.XXX-XXX.XXX-XXX-/api/v1/pods

我的代码是:


configuration = client.Configuration()

configuration.host = 'https://api-XXXX'
configuration.ssl_ca_cert = '/XXX/xxx.crt'
configuration.cert_file = '/XXX/xxx.crt'
configuration.key_file = '/XXX/xxx.key'
configuration.verify_ssl = True

v1 = client.CoreV1Api(client.ApiClient(configuration))

ret = v1.list_pod_for_all_namespaces()

但得到:

urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='XXX', port=443): Max retries exceeded with url: /api/v1/pods (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:618)'),))

如果您有任何想法,我将不胜感激!

1 个答案:

答案 0 :(得分:1)

我只是重现了您的情况,它在python 2.7上完美运行

这是代码:

from kubernetes import client

configuration = client.Configuration()

configuration.host = 'https://10.132.0.25:6443'
configuration.ssl_ca_cert = './ca.crt'
configuration.cert_file = './client.crt'
configuration.key_file = './client.key'
configuration.verify_ssl = True

v1 = client.CoreV1Api(client.ApiClient(configuration))

ret = v1.list_pod_for_all_namespaces()

for i in ret.items:
  print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

...以及结果:

$ python test.py 
192.168.171.66  kube-system     calico-kube-controllers-65b8787765-h7qv7
10.132.0.25     kube-system     calico-node-t4r4v
10.132.0.26     kube-system     calico-node-zbtjm
192.168.171.65  kube-system     coredns-5c98db65d4-rm2qh
192.168.171.67  kube-system     coredns-5c98db65d4-sr67s
10.132.0.25     kube-system     etcd-master
10.132.0.25     kube-system     kube-apiserver-master
10.132.0.25     kube-system     kube-controller-manager-master
10.132.0.26     kube-system     kube-proxy-759gn
10.132.0.25     kube-system     kube-proxy-v5hvc
10.132.0.25     kube-system     kube-scheduler-master

我用kubeadm创建了集群。它正在运行1.15.3

$ kubectl get no
NAME     STATUS   ROLES    AGE   VERSION
master   Ready    master   41m   v1.15.3
worker   Ready    worker   41m   v1.15.3

最后,客户端库:

$ pip freeze | grep -E 'kubernetes|requests'
kubernetes==10.0.1
requests==2.22.0

要进行更多故障排除,需要更多信息。关于版本。但是您的代码可以正常工作。

编辑:它也适用于python3:

$ python3 test.py 
192.168.171.66  kube-system     calico-kube-controllers-65b8787765-h7qv7
10.132.0.25     kube-system     calico-node-t4r4v
10.132.0.26     kube-system     calico-node-zbtjm
192.168.171.65  kube-system     coredns-5c98db65d4-rm2qh
192.168.171.67  kube-system     coredns-5c98db65d4-sr67s
10.132.0.25     kube-system     etcd-master
10.132.0.25     kube-system     kube-apiserver-master
10.132.0.25     kube-system     kube-controller-manager-master
10.132.0.26     kube-system     kube-proxy-759gn
10.132.0.25     kube-system     kube-proxy-v5hvc
10.132.0.25     kube-system     kube-scheduler-master