https://blog.csdn.net/huwh_/article/details/78821805
https://blog.csdn.net/qq_37950254/article/details/89603207
仓库地址: https://github.com/kubernetes-client/go
OpenAPI based generated Go Client for Kubernetes
package main
import (
"context"
"flag"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"log"
)
var clientset *kubernetes.Clientset
func main() {
k8sconfig := flag.String("k8sconfig", "./k8sconfig", "kubernetes config file path")
flag.Parse()
config, err := clientcmd.BuildConfigFromFlags("", *k8sconfig)
if err != nil {
log.Println(err)
}
clientset, err = kubernetes.NewForConfig(config)
if err != nil {
log.Fatalln(err)
} else {
fmt.Println("connect k8s success")
}
//获取POD
//pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
listOptions := metav1.ListOptions{}
pods, err := clientset.CoreV1().Pods("").List(context.Background(), listOptions)
if err != nil {
log.Println(err.Error())
}
fmt.Printf("pod-1名字: %v
", pods.Items[1].Name)
fmt.Printf("pod-1创建时间戳: %v
", pods.Items[1].CreationTimestamp)
fmt.Println(pods.Items[1].Labels)
fmt.Println(pods.Items[1].Namespace)
fmt.Println(pods.Items[1].Status.HostIP)
fmt.Println(pods.Items[1].Status.PodIP)
fmt.Println(pods.Items[1].Status.StartTime)
fmt.Println(pods.Items[1].Status.Phase)
fmt.Println(pods.Items[1].Status.ContainerStatuses[0].RestartCount) //重启次数
fmt.Println(pods.Items[1].Status.ContainerStatuses[0].Image) //获取重启时间
//获取NODE
fmt.Println("------------nodes ----------------")
//nodes, err := clientset.CoreV1().Nodes().List(context1,metav1.ListOptions{})
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), listOptions)
fmt.Println(nodes.Items[0].Name)
fmt.Println(nodes.Items[0].CreationTimestamp) //加入集群时间
fmt.Println(nodes.Items[0].Status.NodeInfo)
fmt.Println(nodes.Items[0].Status.Conditions[len(nodes.Items[0].Status.Conditions)-1].Type)
fmt.Println(nodes.Items[0].Status.Allocatable.Memory().String())
for i, node := range nodes.Items {
fmt.Printf("[%d] %s
", i, node.GetName())
}
}