3

I want to list my k8s jobs with a label selector by client-go like this command:

$ kubectl get jobs -l 'hello-world in (London, China, NewYork)'

I looked through the source code of client-go, then I wrote some code like this:

func listJobs(cli *kubernetes.Clientset) (*batchv1.JobList, error) {
    label := metav1.LabelSelector{
        MatchExpressions: []metav1.LabelSelectorRequirement{
            {
                Key:      "hello-world",
                Operator: metav1.LabelSelectorOpIn,
                Values: []string{
                    "London",
                    "China",
                    "NewYork",
                },
            },
        },
    }

    fmt.Println(label.String())

    return cli.BatchV1().Jobs("default").List(context.TODO(), metav1.ListOptions{
        LabelSelector: label.String(),
    })
}

and then I got the error:

&LabelSelector{MatchLabels:map[string]string{},MatchExpressions:[]LabelSelectorRequirement{LabelSelectorRequirement{Key:hello-world,Operator:In,Values:[London China NewYork],},},}
2021/01/28 17:58:07 unable to parse requirement: invalid label key "&LabelSelector{MatchLabels:map[string]string{}": 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]')

Where did I go wrong? How do I list my jobs with a label selector which is a complex expression?

peterh
  • 11,875
  • 18
  • 85
  • 108
Reed Chan
  • 525
  • 6
  • 16

1 Answers1

5

Using the Kubernetes client-go library, you can simply write label selectors the same way you would with kubectl.

Writing hello-world in (London, China, NewYork) should work just fine.

func listJobs(cli *kubernetes.Clientset) (*batchv1.JobList, error) {
    return cli.BatchV1().Jobs("default").List(context.TODO(), metav1.ListOptions{
        LabelSelector: "hello-world in (London, China, NewYork)",
    })
}

If what you want is to dynamically generate hello-world in (London, China, NewYork) from a programmatic object however, that is another question, which is already answered on StackOverflow here.

Ullaakut
  • 3,554
  • 2
  • 19
  • 34
  • 1
    Thank you very much! This works fine for me. And I figured out another way, I just need to use function `metav1.FormatLabelSelector()` to format my `LabelSelector`, like this: `selector := metav1.FormatLabelSelector(label)`, and then parse the `selector` variable to `LabelSelector` in `ListOptions`, this works too. And I could generate my parameters dynamically in `LabelSelectorRequirement`. – Reed Chan Jan 28 '21 at 11:40
  • Yes, this is the solution that this answer linked towards, at https://stackoverflow.com/questions/56231176/kubernetes-client-go-convert-labelselector-to-label-string, feel free to go there and upvote the answer so that other people can find it easier in the future. – Ullaakut Jan 28 '21 at 11:42