登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-31 10:54:31 131浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《如何通过 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 应该可以正常工作。

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,那么这是另一个问题,stackoverflow here 上已经对此进行了回答。

今天关于《如何通过 client-go 使用复杂的 LabelSelector 列出我的 k8s 作业?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>