kubernetes client-go: convert labelselector to label string

ぃ、小莉子 提交于 2021-02-07 18:29:22

问题


In the kubernetes client-go API (or another library that uses it), is there a utility function to convert a k8s.io/apimachinery/pkg/apis/meta/v1/LabelSelector to a string to fill the field LabelSelector in k8s.io/apimachinery/pkg/apis/meta/v1/ListOptions?

I digged through the code of client-go but I can't find a function like that.

The LabelSelector.Marshall() nor LabelSelector.String() give me that (unsurprisingly, because that's not their purpose, but I tried it anyway).

Background

I have spec descriptions like k8s.io/api/extensions/v1beta1/Deployment, and want to use it's set of selector labels (i.e. the Selector field) to query it's pods using

options := metav1.ListOptions{
    LabelSelector: <stringified labels>,
}

podList, err := clientset.CoreV1().Pods(<namespace>).List(options)

回答1:


You can use LabelSelectorAsMap(LabelSelector) function to convert the labelselector into map[string]string map.

Then, use SelectorFromSet function of package k8s.io/apimachinery/pkg/labels to convert map to selector/strings.

Pseudo code:

import (
    "k8s.io/apimachinery/pkg/labels"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func ListPod(labelSelector metav1.LabelSelector) {

    labelMap := metav1.LabelSelectorAsMap(labelSelector)

    options := metav1.ListOptions{
        LabelSelector: labels.SelectorFromSet(labelMap).String(),
    }

    podList, err := clientset.CoreV1().Pods("<namespace>").List(options)

}


来源:https://stackoverflow.com/questions/56231176/kubernetes-client-go-convert-labelselector-to-label-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!