使用 K8s Python 客户端获取服务选择器

Get Service selectors with K8s Python client

我正在尝试通过 Kubernetes Python Client. I am using list_service_for_all_namespaces 方法获取服务 label selectors 以检索服务,并使用 field_selector 参数对其进行过滤,例如:

...
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)
...

我收到这个错误:

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}

因此,似乎只有namenamespace是有效参数,没有记录:

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

目前我的解决方法是为服务设置与标签选择器相同的标签,然后通过[=17检索它=] 参数,但我希望能够通过 label selectors.

获取它

问题是,从一开始我就需要获取服务后面的端点(后端 pods),但是 API 调用甚至没有返回此信息,所以我虽然会得到选择器,将它们与 pods 上的标签进行匹配,然后我们就开始了,但现在我意识到选择器是不可能得到的。

这个限制太多了。我在想可能是我的方法不对。有谁知道从服务中获取 label selectors 的方法吗?

您应该能够从服务对象中获取选择器,然后使用它来查找与该选择器匹配的所有 pods。

例如(我希望我没有错别字,我的 python 已经生锈了):

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)