如何在golang程序中使用client-go列出k8s集群中的所有Pod?

问题描述

我想使用client-go in go程序列出k8s集群中的所有Pod。 一个使用client-go ??列出k8s集群中所有pod的go程序?

解决方法

假设您正在集群中运行程序,请按照以下方式使用InClusterConfig并调用clientset.CoreV1().Pods("").List(context.TODO(),metav1.ListOptions{})。由于我们没有为命名空间传递任何值,因此它将列出所有命名空间中的所有pod。

func main() {
    // creates the in-cluster config
    config,err := rest.InClusterConfig()
    if err != nil {
        panic(err.Error())
    }
    // creates the clientset
    clientset,err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }
    for {
        // get pods in all the namespaces by omitting namespace
        // Or specify namespace to get pods in particular namespace
        pods,err := clientset.CoreV1().Pods("").List(context.TODO(),metav1.ListOptions{})
        if err != nil {
            panic(err.Error())
        }
        fmt.Printf("There are %d pods in the cluster\n",len(pods.Items))

        // Examples for error handling:
        // - Use helper functions e.g. errors.IsNotFound()
        // - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
        _,err = clientset.CoreV1().Pods("default").Get(context.TODO(),"example-xxxxx",metav1.GetOptions{})
        if errors.IsNotFound(err) {
            fmt.Printf("Pod example-xxxxx not found in default namespace\n")
        } else if statusError,isStatus := err.(*errors.StatusError); isStatus {
            fmt.Printf("Error getting pod %v\n",statusError.ErrStatus.Message)
        } else if err != nil {
            panic(err.Error())
        } else {
            fmt.Printf("Found example-xxxxx pod in default namespace\n")
        }

        time.Sleep(10 * time.Second)
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...