如何通过 client-go 使用复杂的 LabelSelector 列出我的 k8s 作业?

问题描述

我想通过 client-go 像这个命令一样使用标签选择器列出我的 k8s 作业:

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

我查看了client-go的源代码,然后我写了一些这样的代码:

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(),})
}

然后我得到了错误:

&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]')

我哪里做错了?如何使用复杂表达式的标签选择器列出我的工作?

解决方法

使用 Kubernetes client-go 库,您可以像使用 kubectl 一样简单地编写标签选择器。

编写 hello-world in (London,China,NewYork) 应该可以正常工作。

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

如果您想要从编程对象动态生成 hello-world in (London,NewYork),那又是另一个问题,StackOverflow here 上已经回答了这个问题。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...