侧边栏壁纸
博主头像
张种恩博主等级

一个能运维的 JPG 搬运工

  • 累计撰写 703 篇文章
  • 累计创建 60 个标签
  • 累计收到 24 条评论

通过 Kubenretes client-go 获取资源 Yaml

张种恩
2022-04-29 / 0 评论 / 0 点赞 / 21 阅读 / 1,651 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-29,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

最近有个需求需要在运维平台支持查看 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())
}
0

评论区