k8s之operator

官网demo地址

https://github.com/kubernetes/client-go/blob/master/examples

新建mian.go代码

package main

import (
  "context"
  "flag"
  "fmt"
  "log"
  "path/filepath"

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

var clientset *kubernetes.Clientset

func main() {
	var kubeconfig *string
	// 获取配置文件路径
	if home := homedir.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() // flags解析
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) // 根据配置文件生成配置文件对象,这个对象如下面的代码注释
	if err != nil {
		log.Println(err)
		return
	}
	clientset, err = kubernetes.NewForConfig(config) // 根据配置文件对象构建客户端
	if err != nil {
		log.Fatalln(err)
		return
	} else {
		fmt.Println("connect k8s success")
	}

	pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{}) // 获取 pods 列表信息
	if err != nil {
		log.Println(err.Error())
		return
	}

	for index, pod := range pods.Items {
		fmt.Println("pods info", index)
		fmt.Println("pods info", pod.Name)
		fmt.Println("pods info", pod.CreationTimestamp)
		fmt.Println("pods info", pod.Labels)
		fmt.Println("pods namespace", pods.Items[1].Namespace)
		fmt.Println("pods info", pod.Status.HostIP)
		fmt.Println("pods info", pod.Status.PodIP)
		fmt.Println("pods info", pod.Status.StartTime)
		fmt.Println("pods info", pod.Status.Phase)
		fmt.Println("pods info", pod.Status.ContainerStatuses[0].RestartCount) //重启次数
		fmt.Println("pods info", pod.Status.ContainerStatuses[0].Image)        //获取重启时间
	}
	fmt.Println("##################")
	nodes, err := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
	for index, node := range nodes.Items {
		fmt.Println("index info", index)
		fmt.Println("node info ", node.Name)
		fmt.Println("node info ", node.CreationTimestamp) //加入集群时间
		fmt.Println("node info ", node.Status.NodeInfo)
		fmt.Println("node info ", node.Status.Conditions[len(nodes.Items[0].Status.Conditions)-1].Type)
		fmt.Println("node info ", node.Status.Allocatable.Memory().String())
	}
}

执行 go mod tidy 下载对应的三方包

执行代码

connect k8s success
pods info 0
pods info grafana-54b54568fc-qzv46
pods info 2020-06-02 18:07:11 +0800 CST
pods info map[app:grafana chart:grafana heritage:Tiller pod-template-hash:54b54568fc release:istio-system]
pods namespace istio-system
pods info 9.134.74.51
pods info 192.168.10.8
pods info 2020-06-02 18:07:11 +0800 CST
pods info Running
pods info 1
pods info grafana/grafana:6.5.2
pods info 1
.......
posted @   朝阳1  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示