如何在Python中列出kubernetes集群中的所有pod?

如何在Python中列出kubernetes集群中的所有pod?,python,kubernetes,Python,Kubernetes,我正试图在Python3中使用复制kubectl get pods命令。除了,我使用的是一个远程kubernetes集群,而不是我的本地主机。配置主机是一个特定的web地址 以下是我尝试过的: v1 = kubernetes.client.CoreV1Api() print("Listing pods with their IPs:") ret = v1.list_pod_for_all_namespaces(watch=False) for

我正试图在Python3中使用复制
kubectl get pods
命令。除了,我使用的是一个远程kubernetes集群,而不是我的本地主机。配置主机是一个特定的web地址

以下是我尝试过的:

    v1 = kubernetes.client.CoreV1Api()
    print("Listing pods with their IPs:")
    ret = v1.list_pod_for_all_namespaces(watch=False)
    for i in ret.items:
        print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
如中所建议。但是,这默认为搜索我的本地主机,而不是特定的web地址。我知道我可以访问此网址,因为以下内容完全按照预期运行:

import time
import kubernetes.client
from kubernetes.client.rest import ApiException
from pprint import pprint

configuration = kubernetes.client.Configuration()
# Configure API key authorization: BearerToken
configuration.api_key['authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
configuration.api_key_prefix['authorization'] = 'Bearer'

# Defining host is optional and default to http://localhost
configuration.host = "THE WEB HOST I'M USING"

# Enter a context with an instance of the API kubernetes.client
with kubernetes.client.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = kubernetes.client.AdmissionregistrationApi(api_client)
    
    try:
        api_response = api_instance.get_api_group()
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling AdmissionregistrationApi->get_api_group: %s\n" % e)

你们都怎么想?如何强制它检查该主机的POD绕过
localhost
default?

我知道两种解决方案可能对您的情况有所帮助。 我将描述这两种情况,你可以选择哪一种最适合你

使用kubeconfig文件 我建议设置一个
kubeconfig
文件,允许您连接到远程集群。 您可以在文档中找到有关如何配置它的更多信息:

如果配置了
kubeconfig
文件,则可以使用该功能从
kubeconfig
文件加载身份验证和群集信息

我创建了一个简单的
list\u pods\u 1.py
脚本来说明它是如何工作的:

$ cat list_pods_1.py
#!/usr/bin/python3.7
# Script name: list_pods_1.py
import kubernetes.client
from kubernetes import client, config

config.load_kube_config("/root/config")   # I'm using file named "config" in the "/root" directory

v1 = kubernetes.client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
    

$ ./list_pods_1.py 
Listing pods with their IPs:
10.32.0.2       kube-system     coredns-74ff55c5b-5k28b
10.32.0.3       kube-system     coredns-74ff55c5b-pfppk
10.156.15.210   kube-system     etcd-kmaster
10.156.15.210   kube-system     kube-apiserver-kmaster
10.156.15.210   kube-system     kube-controller-manager-kmaster
10.156.15.210   kube-system     kube-proxy-gvxhq
10.156.15.211   kube-system     kube-proxy-tjxch
10.156.15.210   kube-system     kube-scheduler-kmaster
10.156.15.210   kube-system     weave-net-6xqlq
10.156.15.211   kube-system     weave-net-vjm7j
$ cat list_pods_2.py 
#!/usr/bin/python3.7
import kubernetes.client
from kubernetes import client, config
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

 # Define the barer token we are going to use to authenticate.
    # See here to create the token:
    # https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/
aToken = "<MY_TOKEN>"

    # Create a configuration object
aConfiguration = client.Configuration()

    # Specify the endpoint of your Kube cluster
aConfiguration.host = "https://<ENDPOINT_OF_MY_K8S_CLUSTER>"

    # Security part.
    # In this simple example we are not going to verify the SSL certificate of
    # the remote cluster (for simplicity reason)
aConfiguration.verify_ssl = False
    # Nevertheless if you want to do it you can with these 2 parameters
    # configuration.verify_ssl=True
    # ssl_ca_cert is the filepath to the file that contains the certificate.
    # configuration.ssl_ca_cert="certificate"

aConfiguration.api_key = {"authorization": "Bearer " + aToken}

    # Create a ApiClient with our config
aApiClient = client.ApiClient(aConfiguration)

    # Do calls
v1 = client.CoreV1Api(aApiClient)
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" %
            (i.status.pod_ip, i.metadata.namespace, i.metadata.name))



$ ./list_pods_2.py 
Listing pods with their IPs:
10.32.0.2       kube-system     coredns-74ff55c5b-5k28b
10.32.0.3       kube-system     coredns-74ff55c5b-pfppk
10.156.15.210   kube-system     etcd-kmaster
10.156.15.210   kube-system     kube-apiserver-kmaster
10.156.15.210   kube-system     kube-controller-manager-kmaster
10.156.15.210   kube-system     kube-proxy-gvxhq
10.156.15.211   kube-system     kube-proxy-tjxch
10.156.15.210   kube-system     kube-scheduler-kmaster
10.156.15.210   kube-system     weave-net-6xqlq
10.156.15.211   kube-system     weave-net-vjm7j
使用承载令牌 如本例所述-:

是否可以从集群外的服务器与远程Kubernetes集群进行通信,而不在其上安装kube客户端。通过使用承载令牌来保护通信

您可以在文档中看到如何创建和使用令牌

我已经创建了简单的
list\u pods\u 2.py
script( 基于脚本),以说明其工作原理:

$ cat list_pods_1.py
#!/usr/bin/python3.7
# Script name: list_pods_1.py
import kubernetes.client
from kubernetes import client, config

config.load_kube_config("/root/config")   # I'm using file named "config" in the "/root" directory

v1 = kubernetes.client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
    

$ ./list_pods_1.py 
Listing pods with their IPs:
10.32.0.2       kube-system     coredns-74ff55c5b-5k28b
10.32.0.3       kube-system     coredns-74ff55c5b-pfppk
10.156.15.210   kube-system     etcd-kmaster
10.156.15.210   kube-system     kube-apiserver-kmaster
10.156.15.210   kube-system     kube-controller-manager-kmaster
10.156.15.210   kube-system     kube-proxy-gvxhq
10.156.15.211   kube-system     kube-proxy-tjxch
10.156.15.210   kube-system     kube-scheduler-kmaster
10.156.15.210   kube-system     weave-net-6xqlq
10.156.15.211   kube-system     weave-net-vjm7j
$ cat list_pods_2.py 
#!/usr/bin/python3.7
import kubernetes.client
from kubernetes import client, config
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

 # Define the barer token we are going to use to authenticate.
    # See here to create the token:
    # https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/
aToken = "<MY_TOKEN>"

    # Create a configuration object
aConfiguration = client.Configuration()

    # Specify the endpoint of your Kube cluster
aConfiguration.host = "https://<ENDPOINT_OF_MY_K8S_CLUSTER>"

    # Security part.
    # In this simple example we are not going to verify the SSL certificate of
    # the remote cluster (for simplicity reason)
aConfiguration.verify_ssl = False
    # Nevertheless if you want to do it you can with these 2 parameters
    # configuration.verify_ssl=True
    # ssl_ca_cert is the filepath to the file that contains the certificate.
    # configuration.ssl_ca_cert="certificate"

aConfiguration.api_key = {"authorization": "Bearer " + aToken}

    # Create a ApiClient with our config
aApiClient = client.ApiClient(aConfiguration)

    # Do calls
v1 = client.CoreV1Api(aApiClient)
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" %
            (i.status.pod_ip, i.metadata.namespace, i.metadata.name))



$ ./list_pods_2.py 
Listing pods with their IPs:
10.32.0.2       kube-system     coredns-74ff55c5b-5k28b
10.32.0.3       kube-system     coredns-74ff55c5b-pfppk
10.156.15.210   kube-system     etcd-kmaster
10.156.15.210   kube-system     kube-apiserver-kmaster
10.156.15.210   kube-system     kube-controller-manager-kmaster
10.156.15.210   kube-system     kube-proxy-gvxhq
10.156.15.211   kube-system     kube-proxy-tjxch
10.156.15.210   kube-system     kube-scheduler-kmaster
10.156.15.210   kube-system     weave-net-6xqlq
10.156.15.211   kube-system     weave-net-vjm7j

你所说的“网络主机”是什么意思。它需要Kubernetes API服务的URL和其他配置。通常,这来自于你的
.kube/config
文件,就像kubectl和所有其他Kubernetes客户端工具一样。你不需要将
api\u客户端
传递到
CoreV1Api
,比如
Kubernetes.client.CoreV1Api(api\u客户端)
?通常你会将
config
文件放在
/.kube//code>下,在这种情况下,您只需执行
config.load\u kube\u config()
,因为API默认为
~/.kube/config
。是的,这是真的,谢谢您的注意:)我想说明配置此路径是可能的。matt\u j,非常感谢您的帮助。看起来这给了我一些好的进展,但我遇到了一个新问题。首先,我发现我确实需要使用SSL,因为它不会让我离开。(因此我取消了相关行的注释,并注释掉了不相关的行)。现在遇到此错误:
urllib3.exceptions.SSLError:[Errno 2]没有这样的文件或目录
。你知道如何克服这个问题吗<代码>文件“~/venv/lib/python3.9/site packages/urllib3/util/ssl_uu.py”,第381行,在ssl_-wrap_套接字上下文中。加载_-verify_位置(ca_-certs、ca_-cert_dir、ca_-cert_-data)
使用venvverify*ssl,我的意思是说,正如我被要求使用:
configuration.verify\u-ssl=True-configuration.ssl.ssl\u-ca_-cert=“cert”
您的
ssl\u ca\u证书可能不在适当的位置。您是如何从群集检索CA证书的。我准备了从
kubeconfig
文件中检索此证书的命令:
cat.kube/config | grep证书颁发机构数据| cut-f2-d:| xargs | base64--decode
它可能对您有用。