文章目录

  • 1.获取pod,pv,pvc,namespace数量并打印
    • go.mod
    • client.go
  • 2. 打印pod详细信息

1.获取pod,pv,pvc,namespace数量并打印

go.mod

module clientgo 1.13require (github.com/evanphx/json-patch v4.9.0+incompatible // indirectgithub.com/fsnotify/fsnotify v1.4.9 // indirectgithub.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7 // indirectgithub.com/golang/protobuf v1.4.2 // indirectgithub.com/googleapis/gnostic v0.4.0 // indirectgithub.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirectgithub.com/imdario/mergo v0.3.11 // indirectgithub.com/json-iterator/go v1.1.10 // indirectgithub.com/pkg/errors v0.9.1 // indirectgolang.org/x/net v0.0.0-20200707034311-ab3426394381 // indirectgolang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4 // indirectgolang.org/x/text v0.3.3 // indirectgolang.org/x/time v0.0.0-20200630173020-3af7569d3a1e // indirectgoogle.golang.org/protobuf v1.24.0 // indirectk8s.io/apimachinery v0.17.0k8s.io/client-go v0.17.0k8s.io/gengo v0.0.0-20200413195148-3a45101e95ac // indirectk8s.io/klog/v2 v2.2.0 // indirectk8s.io/utils v0.0.0-20201110183641-67b214c5f920 // indirectsigs.k8s.io/structured-merge-diff/v4 v4.0.1 // indirect
)

client.go

package main
import ("flag"
//    "context""fmt""os""path/filepath"metav1 "k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/client-go/kubernetes""k8s.io/client-go/tools/clientcmd"
)
func main() {var kubeconfig *stringif home := homeDir(); home != "" {kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")} else {kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")}flag.Parse()// uses the current context in kubeconfigconfig, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)if err != nil {panic(err.Error())}// creates the clientsetclientset, err := kubernetes.NewForConfig(config)if err != nil {panic(err.Error())}pods, err1 := clientset.CoreV1().Pods("").List(metav1.ListOptions{})if err1 != nil {panic(err1.Error())}pvs, err2 := clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})if err2 != nil {panic(err2.Error())}pvcs, err3 := clientset.CoreV1().PersistentVolumeClaims("").List(metav1.ListOptions{})if err3 != nil {panic(err3.Error())}namespaces, err4 := clientset.CoreV1().Namespaces().List(metav1.ListOptions{})if err4 != nil {panic(err4.Error())}fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))fmt.Printf("There are %d pvs in the cluster\n", len(pvs.Items))fmt.Printf("There are %d pvcs in the cluster\n", len(pvcs.Items))fmt.Printf("There are %d namespaces in the cluster\n", len(namespaces.Items))fmt.Println("---------pods----------")for _, pod := range pods.Items {fmt.Printf("Name: %s, Status: %s, CreateTime: %s\n", pod.ObjectMeta.Name, pod.Status.Phase, pod.ObjectMeta.CreationTimestamp)}fmt.Println("---------pvs----------")for _, pv := range pvs.Items {fmt.Printf("Name: %s, Status: %s, CreateTime: %s\n", pv.ObjectMeta.Name, pv.Status.Phase, pv.ObjectMeta.CreationTimestamp)}fmt.Println("---------pvcs----------")for _, pvc := range pvcs.Items {fmt.Printf("Name: %s, Status: %s, CreateTime: %s\n", pvc.ObjectMeta.Name, pvc.Status.Phase, pvc.ObjectMeta.CreationTimestamp)}fmt.Println("---------namespaces----------")for _, namespace := range namespaces.Items {fmt.Printf("Name: %s, Status: %s, CreateTime: %s\n", namespace.ObjectMeta.Name, namespace.Status.Phase, namespace.ObjectMeta.CreationTimestamp)}
}
func homeDir() string {if h := os.Getenv("HOME"); h != "" {return h}return os.Getenv("USERPROFILE") // windows
}

执行:

$ go run client.go
There are 4 pods in the cluster
There are 2 pvs in the cluster
There are 2 pvcs in the cluster
There are 6 namespaces in the cluster
---------pods----------
Name: backend, Status: Running, CreateTime: 2020-10-23 02:24:45 -0700 PDT
Name: database, Status: Running, CreateTime: 2020-10-23 02:24:45 -0700 PDT
Name: frontend, Status: Running, CreateTime: 2020-10-23 02:24:45 -0700 PDT
Name: backend, Status: Running, CreateTime: 2020-10-24 02:34:47 -0700 PDT
---------pvs----------
Name: pv, Status: Bound, CreateTime: 2020-09-28 19:19:46 -0700 PDT
Name: task-pv-volume, Status: Bound, CreateTime: 2020-11-27 04:34:38 -0800 PST
---------pvcs----------
Name: pvc, Status: Bound, CreateTime: 2020-09-28 19:23:51 -0700 PDT
Name: task-pv-claim, Status: Bound, CreateTime: 2020-11-28 06:27:54 -0800 PST
---------namespaces----------
Name: app-stack, Status: Active, CreateTime: 2020-09-28 19:00:18 -0700 PDT
Name: default, Status: Active, CreateTime: 2020-09-25 23:11:56 -0700 PDT
Name: kube-node-lease, Status: Active, CreateTime: 2020-09-25 23:11:55 -0700 PDT
Name: kube-public, Status: Active, CreateTime: 2020-09-25 23:11:55 -0700 PDT
Name: kube-system, Status: Active, CreateTime: 2020-09-25 23:11:54 -0700 PDT
Name: rq-demo, Status: Active, CreateTime: 2020-10-22 20:01:59 -0700 PDT

2. 打印pod详细信息

package mainimport ("flag""fmt""os""path/filepath""time""k8s.io/apimachinery/pkg/api/errors"metav1 "k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/client-go/kubernetes""k8s.io/client-go/tools/clientcmd"
)func main() {// 配置 k8s 集群外 kubeconfig 配置文件,默认位置 $HOME/.kube/configvar kubeconfig *stringif home := homeDir(); home != "" {kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")} else {kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")}flag.Parse()//在 kubeconfig 中使用当前上下文环境,config 获取支持 url 和 path 方式config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)if err != nil {panic(err.Error())}// 根据指定的 config 创建一个新的 clientsetclientset, err := kubernetes.NewForConfig(config)if err != nil {panic(err.Error())}for {// 通过实现 clientset 的 CoreV1Interface 接口列表中的 PodsGetter 接口方法 Pods(namespace string) 返回 PodInterface// PodInterface 接口拥有操作 Pod 资源的方法,例如 Create、Update、Get、List 等方法// 注意:Pods() 方法中 namespace 不指定则获取 Cluster 所有 Pod 列表pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})if err != nil {panic(err.Error())}fmt.Printf("There are %d pods in the k8s cluster\n", len(pods.Items))// 获取指定 namespace 中的 Pod 列表信息namespace := "default"pods, err = clientset.CoreV1().Pods(namespace).List(metav1.ListOptions{})if err != nil {panic(err)}fmt.Printf("\nThere are %d pods in namespaces %s\n", len(pods.Items), namespace)for _, pod := range pods.Items {fmt.Printf("Name: %s, Status: %s, CreateTime: %s\n", pod.ObjectMeta.Name, pod.Status.Phase, pod.ObjectMeta.CreationTimestamp)}// 获取指定 namespaces 和 podName 的详细信息,使用 error handle 方式处理错误信息namespace = "default"podName := "backend"pod, err := clientset.CoreV1().Pods(namespace).Get(podName, metav1.GetOptions{})if errors.IsNotFound(err) {fmt.Printf("Pod %s in namespace %s not found\n", podName, namespace)} else if statusError, isStatus := err.(*errors.StatusError); isStatus {fmt.Printf("Error getting pod %s in namespace %s: %v\n",podName, namespace, statusError.ErrStatus.Message)} else if err != nil {panic(err.Error())} else {fmt.Printf("\nFound pod %s in namespace %s\n", podName, namespace)maps := map[string]interface{}{"Name":        pod.ObjectMeta.Name,"Namespaces":  pod.ObjectMeta.Namespace,"NodeName":    pod.Spec.NodeName,"Annotations": pod.ObjectMeta.Annotations,"Labels":      pod.ObjectMeta.Labels,"SelfLink":    pod.ObjectMeta.SelfLink,"Uid":         pod.ObjectMeta.UID,"Status":      pod.Status.Phase,"IP":          pod.Status.PodIP,"Image":       pod.Spec.Containers[0].Image,}prettyPrint(maps)
//                        fmt.Println(maps)}time.Sleep(10 * time.Second)}
}
//分列输出
func prettyPrint(maps map[string]interface{}) { lens := 0for k, _ := range maps {if lens <= len(k) {lens = len(k)}fmt.Println(lens)}for key, values := range maps {spaces := lens - len(key)v := ""for i := 0; i < spaces; i++ {v += " "}fmt.Printf("%s: %s%v\n", key, v, values)}
}func homeDir() string {if h := os.Getenv("HOME"); h != "" {return h}return os.Getenv("USERPROFILE") // windows
}

输出:

root@master:~/k8s_dev/client_pod_details# go run client.go
There are 21 pods in the k8s clusterThere are 6 pods in namespaces default
Name: backend, Status: Running, CreateTime: 2020-10-24 02:34:47 -0700 PDT
Name: delpersistentvolumeclaims-1606753860-xfkgx, Status: Succeeded, CreateTime: 2020-11-30 08:31:02 -0800 PST
Name: delpersistentvolumeclaims-1606753920-hftgz, Status: Succeeded, CreateTime: 2020-11-30 08:32:03 -0800 PST
Name: delpersistentvolumeclaims-1606753980-j8k76, Status: Succeeded, CreateTime: 2020-11-30 08:33:03 -0800 PST
Name: patch-demo-76b69ff5cd-htjmd, Status: Running, CreateTime: 2020-10-24 02:59:29 -0700 PDT
Name: patch-demo-76b69ff5cd-hwzd5, Status: Running, CreateTime: 2020-11-30 04:42:15 -0800 PSTFound pod backend in namespace default
Name:        backend
NodeName:    node2
IP:          192.168.104.34
Image:       nginx
Uid:         1c206880-592b-4ad1-89bb-26bd51e8ddf5
Status:      Running
Namespaces:  default
Annotations: map[cni.projectcalico.org/podIP:192.168.104.34/32]
Labels:      map[]
SelfLink:    /api/v1/namespaces/default/pods/backend

kubernetes dev client-go 输出资源相关推荐

  1. Kubernetes Python Client

    一.概述 Kubernetes官方维护的Python客户端client-python, 地址:https://github.com/kubernetes-client/python 安装模块 pip3 ...

  2. Linux企业运维——Kubernetes(三)Pod资源清单

    Linux企业运维--Kubernetes(三)Pod资源清单 文章目录 Linux企业运维--Kubernetes(三)Pod资源清单 一.资源 1.1.资源分类 1.2.资源清单 二.实践操作 2 ...

  3. 如何在kubernetes中使用共享GPU资源

    目录 背景 Kubernetes如何使用物理GPU Kubernetes如何使用共享GPU算力 背景 作为推动人工智能技术进步的"三驾马车",算法.数据和计算力在过去的5-10年间 ...

  4. Kubernetes(k8s)常用资源的使用、Pod的常用操作

    1.K8s是如何运行容器的. 答:k8s是通过定义一个Pod的资源,然后在Pod里面运行容器的.K8s最小的资源单位Pod. 2.如何创建一个Pod资源呢? 答:在K8s中,所有的资源单位都可以使用一 ...

  5. kubernetes dev client-go 介绍

    文章目录 1. 简介 2. Setup 3. 连接 API Server 4. 创建一个clientset 5. 获取集群的PVC列表 6. 监听集群中pvc 6.1 启动监听功能 6.2 循环事件 ...

  6. 使用gatekeeper限制kubernetes创建特定类型的资源

    正常情况下用户要登录k8s创建某资源比如pod时,首先apiserver会检测 1.通过token或者证书认证此用户是否能够登录k8s 2.会检测此用户是否具备足够的权限 在k8s默认的情况下,如果用 ...

  7. #yyds干货盘点# Kubernetes 怎样控制业务的资源水位?(16)

    相信你已经见识到了 Kubernetes 的强大能力,它能帮你轻松管理大规模的容器服务,尤其是面对复杂的环境时,比如节点异常.容器异常退出等,Kubernetes 内部的 Service.Deploy ...

  8. kubernetes和docker----2.学习Pod资源

    Pod–k8s最基础的资源 我们想要的是单个容器只运行一个进程 然而有时我们需要多个进程协同工作,所以我们需要另外一种更加高级的结构将容器组合在一起-pod Pod 我们来看一个最基本的pod 这个p ...

  9. Kubernetes基本入门-名称空间资源(三)

    名称空间级资源 名称空间在kubernetes中主要的作用是做资源隔离,因此名称空间级别的资源只在当前名称空间下有效. 工作负载型资源 工作负载(workload)是在Kubernetes上运行的应用 ...

最新文章

  1. php in yii framework
  2. R对数秩检验(log rank test)
  3. logstash入门
  4. STM32高级开发(12)-在GCC中使用printf打印串口数据
  5. SQL查询中having和where的异同点
  6. linux文件IO——文件IO介绍
  7. Spring实现多数据源配置
  8. jQuery--基本选择器
  9. 一维稳态导热的数值计算c语言,传热传质上机实习题(参考资料C语言)
  10. 利用HTML制作简易新闻网站的静态网页
  11. rabbitmq使用_RabbitMQ 简介以及使用场景
  12. 程序员试用期被裁,只给半个月赔偿
  13. 高数复习(1)--曲线切向与曲面法向的理解
  14. 今秋如何让自己的C币也来个大丰收
  15. 【C语言】指针的理解(乱七芭蕉)
  16. 生理学_神经系统的功能
  17. Mac电脑如何录制视频?三种录制流视频的方法带给大家
  18. C++ 虚函数表 vfptr
  19. BreederDAO 宣布与 20 多个区块链游戏建立官方合作关系
  20. Legolas工业自动化平台入门(三)交互事件响应动作

热门文章

  1. linux为什么不需要磁盘碎片整理,Linux不用磁盘碎片整理原因分析.doc
  2. 【java】生成13位条形码(Ean-13码)
  3. pandas中drop用法_机器学习笔记:Pandas的delete、drop函数的用法
  4. 4天上线“战疫”小程序,腾讯敏捷在数字广东的落地实践
  5. python3可视化-pyecharts图形库,利用Map进行地图的创建和使用
  6. iSCSI initiator
  7. Win11系统管理应用程序将更便利,微软正在测试改进中
  8. iOS开发者问题答疑——买号、关联、刷评论
  9. Xshell和xftp免费下载与使用
  10. 2022元宇宙十大 “闪光时刻”