2019-05-21 04:38

kubernetes client-go:将labelselector转换为标签字符串


In the kubernetes client-go API (or another library that uses it), is there a utility function to convert a to a string to fill the field LabelSelector in

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


I have spec descriptions like, 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)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dp198879 dp198879 2年前

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

    Then, use SelectorFromSet function of package to convert map to selector/strings.

    Pseudo code:

    import (
        metav1 ""
    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)
    点赞 评论 复制链接分享