0

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?

Nathan Long
  • 122,748
  • 97
  • 336
  • 451
  • 1
    I hope I'm not misreading the question, but you can just run `kubectl` in your pod (or make the equivalent api call). You will need to authenticate using a serviceaccount. – larsks Mar 01 '21 at 19:42
  • My pod doesn't have `kubectl` installed. I suppose I could include it in the image, but that seems odd. I'll look into using the API. – Nathan Long Mar 01 '21 at 20:00
  • 1
    What is actually the reason for getting the list of pods? – Manuel Mar 01 '21 at 22:23
  • 1
    you can look at several [supported client libraries](https://kubernetes.io/docs/reference/using-api/client-libraries/) and install in your image as per your need. – Krishna Chaurasia Mar 02 '21 at 05:42
  • Any specific reason for listing all the pods exposed by a particular service ? Could you elaborate a bit more on your use case and explain what you actually want to achieve by that ? Using client libraries seems to me quite reasonable option. – mario Mar 02 '21 at 18:39
  • My thought was to write a custom load balancer for that service, but on further thought, having the pods pull work from RabbitMQ as they're able to handle it makes more sense – Nathan Long Mar 10 '21 at 19:29

1 Answers1

0

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.

mario
  • 9,858
  • 1
  • 26
  • 42