通过 Kubenretes client-go 获取 Deployment Yaml

2022-06-23 10:55:03

最近有个需求需要在运维平台支持查看 Kubernetes 资源 Yaml,查看了下 kubectl 源码的实现,藏得比较深,所以记录一下。

/**
 * @Author: zze
 * @Date: 2022/4/21 11:43
 * @Desc:
 */
package main

import (
    "bytes"
    "context"
    "fmt"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/runtime/schema"
    "k8s.io/cli-runtime/pkg/printers"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/clientcmd"
    "strings"
)

type K8sClient struct {
    RestConf  *rest.Config
    ClientSet *kubernetes.Clientset
}

func NewK8sClient(conf string) (*K8sClient, error) {
    k8sClient := new(K8sClient)
    var err error
    if k8sClient.RestConf, err = GetRestConf(conf); err != nil {
        return nil, err
    }
    if k8sClient.ClientSet, err = kubernetes.NewForConfig(k8sClient.RestConf); err != nil {
        return nil, err
    }
    return k8sClient, nil
}

func GetRestConf(config string) (*rest.Config, error) {
    var (
        restConf *rest.Config
        err      error
    )

    if restConf, err = clientcmd.RESTConfigFromKubeConfig([]byte(config)); err != nil {
        return nil, err
    }
    return restConf, nil
}

func main() {
    y := printers.YAMLPrinter{}
    cli, err := NewK8sClient("<kubeConfig>")
    if err != nil {
        panic(err)
    }
    namespace := "<命名空间>"
    deploymentsClient := cli.ClientSet.AppsV1().Deployments(namespace)
    deployment, err := deploymentsClient.Get(context.TODO(), "<Deployment 名称>", metav1.GetOptions{})
    if err != nil {
        if strings.Contains(err.Error(), "not found") {
            panic("not found")
        }
        panic(err)
    }
    deployment.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{
        Group:   "apps",
        Version: "v1",
        Kind:    "Deployment",
    })
    buf := new(bytes.Buffer)
    err = y.PrintObj(deployment, buf)
    if err != nil {
        panic(err)
    }
    fmt.Println(buf.String())
}