首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何按client-go列出具有复杂LabelSelector的k8s作业?

如何按client-go列出具有复杂LabelSelector的k8s作业?
EN

Stack Overflow用户
提问于 2021-01-28 18:03:26
回答 1查看 379关注 0票数 3

我想通过client-go使用标签选择器列出我的k8s作业,如下所示:

代码语言:javascript
运行
复制
$ kubectl get jobs -l 'hello-world in (London, China, NewYork)'

我查看了client-go的源代码,然后写了一些代码,如下所示:

代码语言:javascript
运行
复制
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(),
    })
}

然后我得到了错误:

代码语言:javascript
运行
复制
&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]')

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

EN

回答 1

Stack Overflow用户

发布于 2021-01-28 18:36:44

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

编写hello-world in (London, China, NewYork)应该可以很好地工作。

代码语言:javascript
运行
复制
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)",
    })
}

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65934853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档