kubernetes客户端client-go使用

在最近的一个运维平台中,需要将K8S集成到项目中,因为采用go语言的beego框架写的,所以采用client-go与k8s交互;
简单的测试代码:

package main

import (
    "flag"
    "k8s.io/client-go/tools/clientcmd"
    "log"
    "k8s.io/client-go/kubernetes"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "fmt"
)

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{})
    if err != nil {
        log.Println(err.Error())
    }

    fmt.Println(pods.Items[1].Name)
    fmt.Println(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, err := clientset.CoreV1().Nodes().List(metav1.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())

}

并附上一篇个人比较认可的博客,以供参考
https://blog.csdn.net/huwh_/article/details/78821805

    原文作者:苏州运维开发
    原文地址: https://www.jianshu.com/p/48946a317d81
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞