英文:
Retrieve kubernetes nodes that do not contain label using apimachinery/client-go
问题
我想获取不包含标签的 kubernetes
节点列表(如果有的话)。
我已经使用 client-go
成功实现了相反的操作。
labelSelector := metav1.LabelSelector{
MatchLabels: map[string]string{
"somelabel": "somevalue",
},
}
labelMap, err := metav1.LabelSelectorAsMap(&labelSelector)
if err != nil {
return false, errors.Wrap(err, "将节点标签选择器转换为映射时出错")
}
nodeListOptions := metav1.ListOptions{
LabelSelector: labels.SelectorFromSet(labelMap).String(),
}
nodes, err := clientset.CoreV1().Nodes().List(nodeListOptions)
if err != nil {
return false, errors.Wrap(err, "获取节点列表时出错")
}
我想要实现的是将以下 kubectl
命令转换为 client-go
代码:
kubectl get ns --selector='!label_name'
这个可行吗?
英文:
I want to fetch the list (if any) of kubernetes
nodes that do not contain a label.
I have managed to do the opposite using client-go
labelSelector := metav1.LabelSelector{
MatchLabels: map[string]string{
"somelabel": "somevalue",
},
}
labelMap, err := metav1.LabelSelectorAsMap(&labelSelector)
if err != nil {
return false, errors.Wrap(err, "error converting node label selector to map")
}
nodeListOptions := metav1.ListOptions{
LabelSelector: labels.SelectorFromSet(labelMap).String(),
}
nodes, err := clientset.CoreV1().Nodes().List(nodeListOptions)
if err != nil {
return false, errors.Wrap(err, "error getting node list")
}
What I want to achieve is to convert the following kubectl
invocation
kubectl get ns --selector='!label_name'
into client-go
code.
Is this feasible?
答案1
得分: 2
我认为你需要使用apimachinery
的labels
包中的Requirement
类型,并基于此创建Selector
构造。
nodeReq, err := labels.NewRequirement("label_name", selection.DoesNotExist, []string{})
if err != nil {
return false, errors.Wrap(err, "error creating selector requirement")
}
selector := labels.NewSelector()
selector = selector.Add(*nodeReq)
if err != nil {
return false, errors.Wrap(err, "error converting node label selector to map")
}
nodeListOptions := metav1.ListOptions{
LabelSelector: selector.String(),
}
nodes, err := clientset.CoreV1().Nodes().List(nodeListOptions)
英文:
I think one has to use the Requirement
type of the apimachinery
's labels
package and create Selector
constructs based on this.
nodeReq, err := labels.NewRequirement("label_name", selection.DoesNotExist, []string{})
if err != nil {
return false, errors.Wrap(err, "error creating selector requirement")
}
selector := labels.NewSelector()
selector = selector.Add(*nodeReq)
if err != nil {
return false, errors.Wrap(err, "error converting node label selector to map")
}
nodeListOptions := metav1.ListOptions{
LabelSelector: selector.String(),
}
nodes, err := clientset.CoreV1().Nodes().List(nodeListOptions)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论