Kubernetes API - gets Pods on specific nodes

前端 未结 6 1218
故里飘歌
故里飘歌 2020-12-23 00:40

Looking at http://kubernetes.io/docs/user-guide/labels/#selecting-sets-of-nodes it looks to be possible to select a certain range of pods based on labels. But in my case I w

6条回答
  •  没有蜡笔的小新
    2020-12-23 00:58

    I've gone through the same process with the Go Client and it uncovers a few shortcuts the CLI is taking.

    func doNodesHavePods(clientset *kubernetes.Clientset) error {
        nodeLabelSelector := "nodelabel=interesting_nodes"
        nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{LabelSelector: nodeLabelSelector})
    
        if err != nil {
            return err
        }
    
        nodeNames := []string{}
        for _, node := range nodes.Items {
            nodeNames = append(nodeNames, node.Name)
        }
        // --all-namespaces -> listing and looping on namespaces
        namespaces, err := clientset.CoreV1().Namespaces().List(metav1.ListOptions{})
    
        if err != nil {
            return err
        }
        for _, namespace := range namespaces.Items {
            for _, name := range nodeNames {
                // pods need a namespace to be listed.
                pods, err := clientset.CoreV1().Pods(namespace.Name).List(metav1.ListOptions{FieldSelector: "spec.nodeName=" + name})
                if err != nil {
                    println("%v", err)
                }
                for _, pod := range pods.Items {
                    fmt.Println(pod.Namespace, pod.Name)
                }
            }
        }
        return nil
    }
    

    I've started to find that a lot of the questions I need to ask are becoming too complex for the CLI which is a great workhorse, but learning to use the Go Client can help you get the first answer you're looking for, but also dig deeper into questions that those answers raise.

提交回复
热议问题