问题描述
在kubernetes client-go API(或使用它的另一个库)中,是否有实用程序函数将k8s.io/apimachinery/pkg/apis/meta/v1/LabelSelector
转换为字符串以填充k8s.io/apimachinery/pkg/apis/meta/v1/ListOptions
中的字段LabelSelector
?
In the kubernetes client-go API (or another library that uses it), is there a utility function to convert a k8s.io/apimachinery/pkg/apis/meta/v1/LabelSelector
to a string to fill the field LabelSelector
in k8s.io/apimachinery/pkg/apis/meta/v1/ListOptions
?
我浏览了client-go
的代码,但找不到类似的功能.
I digged through the code of client-go
but I can't find a function like that.
LabelSelector.Marshall()
或LabelSelector.String()
都给了我(毫不奇怪,因为那不是他们的目的,但我还是尝试了).
The LabelSelector.Marshall()
nor LabelSelector.String()
give me that (unsurprisingly, because that's not their purpose, but I tried it anyway).
我有类似k8s.io/api/extensions/v1beta1/Deployment
的规格说明,并想使用它的选择器标签集(即Selector
字段)来使用
I have spec descriptions like k8s.io/api/extensions/v1beta1/Deployment
, and want to use it's set of selector labels (i.e. the Selector
field) to query it's pods using
options := metav1.ListOptions{
LabelSelector: <stringified labels>,
}
podList, err := clientset.CoreV1().Pods(<namespace>).List(options)
推荐答案
您可以使用LabelSelectorAsMap(LabelSelector)
函数将labelselector转换为map[string]string
映射.
You can use LabelSelectorAsMap(LabelSelector)
function to convert the labelselector into map[string]string
map.
然后,使用软件包k8s.io/apimachinery/pkg/labels
的SelectorFromSet
函数将map
转换为选择器/字符串.
Then, use SelectorFromSet
function of package k8s.io/apimachinery/pkg/labels
to convert map
to selector/strings.
伪代码:
import (
"k8s.io/apimachinery/pkg/labels"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func ListPod(labelSelector metav1.LabelSelector) {
labelMap := metav1.LabelSelectorAsMap(labelSelector)
options := metav1.ListOptions{
LabelSelector: labels.SelectorFromSet(labelMap).String(),
}
podList, err := clientset.CoreV1().Pods("<namespace>").List(options)
}
这篇关于kubernetes client-go:将labelselector转换为标签字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!