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

Cam*_*m I 2 python kubernetes

我正在尝试使用kubernetes python 库kubectl get pods在 Python3 中复制该命令。除此之外,我正在使用远程 kubernetes 集群,而不是我的本地主机。配置主机是一个特定的网址。

这是我尝试过的:

    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))
Run Code Online (Sandbox Code Playgroud)

正如文档中建议的那样。然而,这默认搜索我的本地主机而不是特定的网址。我知道我可以访问该网址,因为以下内容完全 100% 按预期运行:

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)
Run Code Online (Sandbox Code Playgroud)

大家觉得怎么样?如何强制它检查该主机的 pod 是否绕过localhost默认值?

mat*_*t_j 5

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

使用 kubeconfig 文件

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

如果您kubeconfig配置了文件,则可以使用load_kube_config()函数从文件加载身份验证和集群信息kubeconfig

我创建了一个简单的list_pods_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
Run Code Online (Sandbox Code Playgroud)

使用不记名令牌

如本例所述-remote_cluster.py

是否可以从集群外部的服务器与远程 Kubernetes 集群进行通信,而无需安装 kube 客户端。使用Bearer token来保证通信的安全。

您可以在访问集群文档中了解如何创建和使用令牌。

我创建了一个简单的list_pods_2.py脚本(基于remote_cluster.py脚本)来说明它是如何工作的:

$ 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
Run Code Online (Sandbox Code Playgroud)

注意:作为示例,我使用默认服务帐户的令牌(您可能希望使用不同的令牌ServiceAcccount),但要使其正常工作,ServiceAccount需要适当的权限。
例如,您可以像这样添加一个view角色ServiceAccount

$ kubectl create clusterrolebinding --serviceaccount=default:default --clusterrole=view default-sa-view-access
clusterrolebinding.rbac.authorization.k8s.io/default-sa-view-access created
Run Code Online (Sandbox Code Playgroud)