HAOJX

通过labelSelector来选择pod操作

字数统计: 172阅读时长: 1 min
2021/10/25 Share

例子1

1
2
3
4
5
6
7
8
9
10
11
//根据label批量删除pod
labelPod := labels.SelectorFromSet(labels.Set(map[string]string{generalLabelKey: redisClusterName}))
listPodOptions := metav1.ListOptions{
LabelSelector: labelPod.String(),
}
err = kubeClient.CoreV1().Pods(redisClusterNamespace).DeleteCollection(&metav1.DeleteOptions{}, listPodOptions)
if err != nil {
if !errors.IsNotFound(err) {
klog.Errorf("Drop RedisCluster: %v/%v pod error: %v", redisClusterNamespace, redisClusterName, err)
return err
}

例子2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func main() {
client:=lib.InitClient()
dep,_:=client.AppsV1().Deployments("kube-system").Get(context.Background(),"kube-apiserver-node01",v1.GetOptions{})

selector,err:=v1.LabelSelectorAsSelector(dep.Spec.Selector)
if err != nil {
log.Fatal(err)
}
listopt:=v1.ListOptions{
LabelSelector: selector.String(),
}
rs,_:=client.AppsV1().ReplicaSets("kube-system").List(context.Background(),listopt)

for _,item:= range rs.Items{
fmt.Println(item.Name)
}

}

例子2是通过deployment的标签和取出所有rs

例子2里面的 selector.string() 就是取出了这个label标签

CATALOG