<p>I am trying to get Service <code>label selectors</code> through <a href="https://github.com/kubernetes-client/python" rel="nofollow noreferrer">Kubernetes Python Client</a>. I am using <a href="https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md#list_service_for_all_namespaces" rel="nofollow noreferrer">list_service_for_all_namespaces</a> method to retrieve the services, and filter it with <code>field_selector</code> parameter like:</p>

<pre><code>...
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)
...
</code></pre>

<p>I get this error:</p>

<pre><code>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}
</code></pre>

<p>So, it seems that only <code>name</code> and <code>namespace</code> are valid parameters, which is not documented:</p>

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

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

<p>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. </p>

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

suren
<p>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.</p>

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

<pre><code>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"} =&gt; "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)
</code></pre>
