【问题标题】:Get Service selectors with K8s Python client使用 K8s Python 客户端获取服务选择器
【发布时间】:2018-06-28 09:09:23
【问题描述】:

我正在尝试通过Kubernetes Python Client 获得服务label selectors。我正在使用list_service_for_all_namespaces 方法来检索服务,并使用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 |通过字段限制返回对象列表的选择器。默认为一切。 (可选)

目前我的解决方法是为服务设置与 label selectors 相同的 labels,然后通过 label_selector 参数检索它,但我想可以通过label selectors获取。

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

这是太多的限制。我在想可能是我的方法是错误的。有人知道从服务中获取label selectors 的方法吗?

【问题讨论】:

    标签: kubernetes kubernetes-python-client


    【解决方案1】:

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

    例如(我希望我没有错别字,而且我的 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)
    

    【讨论】:

    • 这是有效的。但这是纯python技能。我希望 API 以某种方式返回此信息。谢谢!
    猜你喜欢
    • 2019-03-07
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2017-09-20
    • 2017-03-24
    • 1970-01-01
    相关资源
    最近更新 更多