使用client-go在k8s集群外读取pod资源

使用client-go在k8s集群外读取pod资源,第1张

文章目录 1. 安装client-go和apimachinery2. 运行go程序

1. 安装client-go和apimachinery
go get k8s.io/client-go/...
go get -u k8s.io/apimachinery/...    // -u 表示更新已有的包
2. 运行go程序

main.go

package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	var kubeconfig *string
	// 获取k8s配置文件kubeconfig的地址
	if home := homeDir(); home != "" { // 接受命令行中的name参数, go run main.go --kubeconfig=xxx
		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()
	fmt.Println(*kubeconfig)

	// 使用k8s.io/client-go/tools/clientcmd生成config的对象
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	/// 使用k8s.io/client-go/kubernetes生成一个ClientSet的客户端
	// 客户端生成后,就可以使用这个客户端与k8s API server进行交互,如Create/Retrieve/Update/Delete Resource
	clientset, 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(context.TODO(), 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(context.TODO(), metav1.ListOptions{})
		if err != nil {
			panic(err)
		}
		fmt.Printf("There are %d pods in the namespace %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)
		}
		fmt.Println()
		time.Sleep(3 * time.Second)
	}
}

func homeDir() string {
	if home := os.Getenv("HOME"); home != "" {
		return home
	}
	return os.Getenv("USERPROFILE") // windows
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/995601.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存