简体   繁体   中英

Can a pod within my cluster get a list of pods in a service?

Suppose I have a Service within my cluster called workers . From kubectl , I can list the pods in that service using the selector the service uses:

kubectl get pods --selector app=worker

Can a pod within the cluster get a list of that service's pods?

You can achieve it quite easily with Kubernetes Python Client library . The following code can be run locally as it uses your .kube/config file for authentication:

from  kubernetes import client , config
config.load_kube_config()
v1 = client.CoreV1Api()
list_pods = v1.list_pod_for_all_namespaces(label_selector="app=worker")
for item in list_pods.items:
    print(item.metadata.name)

Before that you will need to install the mentioned library, which can be done with pip :

pip3 install kubernetes

For production use I would recommend integrating it with your python docker image and of course instead of using .kube/config file, you will need to create a ServiceAccount for your client Pod so it can authenticate to kubernetes API . This is nicely described in this answer , provided by krelst .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM