如何解决如何在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)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。