go - 如何在golang程序中使用client-go列出k8s集群中的所有pod?
问题描述
我想在 go 程序中使用 client-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)
}
}
推荐阅读
- google-cloud-platform - Google Cloud Scheduler 的权限被拒绝
- javascript - 如何从网站上的用户那里获取某些输入并将这些值作为特定参数传递给我的 javascript 函数?
- go - dep 注入的模拟接口返回类型
- firebase-authentication - 如何在 iOS NotificationServiceExtension 中检索当前 Firebase 用户?
- python - 在虚拟环境中替换 python 可执行文件,获取别名
- react-native - TypeError: Null 不是对象(评估 RNLanguages.language)
- delphi - 多个 TFileStreams,TStreamWriter 写入同一个文件
- apache-flink - Flink 异步 IO 运算符与另一个同步运算符链接
- django - Django TypeError:allow_migrate() 为参数 'model_name' 获取了多个值
- r - 如何将函数应用于 data.frame 中的多个类别?