Get Service selectors with K8s Python client

6/27/2018

I am trying to get Service label selectors through Kubernetes Python Client. I am using list_service_for_all_namespaces method to retrieve the services, and filter it with field_selector parameter like:

...
field_selector="spec.selector={u'app': 'redis'}
...
services = v1.list_service_for_all_namespaces(field_selector=field_selector, watch=False)
for service in services.items:
    print(service)
...

I get this error:

HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"\"spec.selector\" is not a known field selector: only \"metadata.name\", \"metadata.namespace\"","reason":"BadRequest","code":400}

So, it seems that only name and namespace are valid parameters, which is not documented:

field_selector = 'field_selector_example' # str | A selector to restrict the list of returned objects by their fields. Defaults to everything. (optional)

For now my workaround is to set the same labels as label selectors to the service, then to retrieve it through label_selector parameter, but I'd like to be able to get it through label selectors.

The thing is that from the beginning I need to get the endpoints behind the service (the backend pods), but the API call is not even returning this information, so I though I would get the selectors, match them against the labels on the pods, and there we go, but now I am realizing the selectors are not possible to get either.

This is too much limitation. I am thinking may be my approach is wrong. Does anyone know a way of getting label selectors from a service?

-- suren
kubernetes
kubernetes-python-client

1 Answer

6/28/2018

You should be able to get the selector from a service object, and then use that to find all the pods that match the selector.

For example (I am hoping I don't have typos, and my python is rusty):

services = v1.list_service_for_all_namespaces(watch=False)
for svc in services.items:
    if svc.spec.selector:
        # convert the selector dictionary into a string selector
        # for example: {"app":"redis"} => "app=redis"
        selector = ''
        for k,v in svc.spec.selector.items():
            selector += k + '=' + v + ','
        selector = selector[:-1]

        # Get the pods that match the selector
        pods = v1.list_pod_for_all_namespaces(label_selector=selector)
        for pod in pods.items:
            print(pod.metadata.name)
-- AlexBrand
Source: StackOverflow