Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LabelSelector for Secrets List in k8s

Tags:

go

kubernetes

I want to get Secret object from k8s cluster using go-client API

I have function that looks like that

func GetSecret( version string) (retVal interface{}, err error){
    clientset := GetClientOutOfCluster()
    labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

    listOptions := metav1.ListOptions{
        LabelSelector: labelSelector.String(),
        Limit:         100,
    }
    secretList, err := clientset.CoreV1().Secrets("namespace").List( listOptions )
    retVal = secretList.Items[0]
    return retVal, err
}

GetClientOutOfCluster is basically retrieves configuration from cluster or from local ~/.kube/config

I used metav1.LabelSelector just like i do when i generate new Deployment object.So i thought i was cool. But ListOptions.LabelSelector is a string. When i run my function it fails.

unable to parse requirement: invalid label key "&LabelSelector{MatchLabels:map[string]string{version:": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName',  or 'my.name',  or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')

I cannot find example of usage of this function anywhere. Documentation assumes that you know what is LabelSelector.

What is format of LabelSelector for ListOptions?

Thanks

like image 999
AlexS Avatar asked Oct 26 '25 18:10

AlexS


2 Answers

You can use the k8s provided function to do the toString operation

import "k8s.io/apimachinery/pkg/labels"
...

func GetSecret(version string) (retVal interface{}, err error){
  clientset := GetClientOutOfCluster()
  labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

  listOptions := metav1.ListOptions{
    LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
    Limit:         100,
  }
  secretList, err := clientset.CoreV1().Secrets("namespace").List(listOptions)
  retVal = secretList.Items[0]
  return retVal, err
}
like image 101
larry.li Avatar answered Oct 29 '25 19:10

larry.li


func GetSecret( version string, param2 string) (retVal interface{}, err error){
    clientset := GetClientOutOfCluster()
    labelSelector := fmt.Sprintf("version=%s, param2=%s", version, param2)

    listOptions := metav1.ListOptions{
        LabelSelector: labelSelector,
        Limit:         100,
    }
    secretList, err := clientset.CoreV1().Secrets("namespace").List( listOptions )
    retVal = secretList.Items[0]
    return retVal, err
}
like image 35
AlexS Avatar answered Oct 29 '25 19:10

AlexS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!