Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get pods by label, using the python kubernetes api?

I am using the python kubernetes api with list_namespaced_pod to get the pods in my namespace. Now I would like to filter them, using the optional label selector parameter.

The documention describes this parameter as

A selector to restrict the list of returned objects by their labels. Defaults to everything.

It does not bother to give an example. On this website, I found several possibilities on how to use the attribute. I already tried

label_selector='label=my_label'
label_selector='label:my_label'
label_selector='my_label'

non of which is working. How do I use the parameter label_selector correctly?

like image 265
A_test_user Avatar asked Sep 18 '18 13:09

A_test_user


People also ask

How do I get pods on a specific label?

There are different methods to manipulate labels in a Pod. If you are create a pod then you can easily assign your labels in the YAML file but for an existing pod you must either edit the object YAML file or use kubectl label command.

How do you get log and describe pods in Kubernetes by Python client?

To get the output of kubectl describe pod , all the information provided is in read_namespaced_pod function. It has all the information you require, and you can use that information in whatever way you require. You can edit the above code and use read_namespaced_pod in place of read_namespaced_pod_log to get the info.

How do I access API from Kubernetes pod?

From inside the pod, kubernetes api server can be accessible directly on "https://kubernetes.default". By default it uses the "default service account" for accessing the api server. So, we also need to pass a "ca cert" and "default service account token" to authenticate with the api server.

How labels work in Kubernetes?

Labels are key/value pairs that are attached to objects, such as pods. Labels are intended to be used to specify identifying attributes of objects that are meaningful and relevant to users, but do not directly imply semantics to the core system. Labels can be used to organize and to select subsets of objects.


2 Answers

Kubernetes CLI uses two types of label selectors.

  1. Equality Based Eg: kubectl get pods -l key=value

  2. Set Based Eg: kubectl get pod -l 'key in (value1,value2)'

label_selector='label=my_label'

should work, else try using

label_selector='label in (my_label1, my_label2)'.

If this does not work the error might come from somewhere else.

like image 142
Jonathan R Avatar answered Sep 22 '22 19:09

Jonathan R


this works for me:

v1.list_namespaced_pod(namespace='default', label_selector='job-name={}'.format(name))
like image 36
hamed Avatar answered Sep 22 '22 19:09

hamed