当前位置: 首页 > 工具软件 > kubectl-slice > 使用案例 >

Client-go 使用kubectl.kubeconfig连接集群的两种方式

唐经国
2023-12-01

第一种方式 clientcmd.BuildConfigFromFlags(masterUrl string, kubeconfigPath string)

func NewBaseClientSet() (*BaseClientSet, error) {
	config, err := clientcmd.BuildConfigFromFlags("", types.KUBE_CONF_FILE)
	if err != nil {
		return nil, err
	}
	clientSet, err := kubernetes.NewForConfig(config)
	if err != nil {
		return nil, err
	}
	baseClient := &BaseClientSet{
		ClientSet: clientSet,
	}
	return baseClient, err
}

第二种方式 clientcmd.RESTConfigFromKubeConfig(data []byte)

该方式读取配置文件内的ca.crt、kubectl.crt、kubectl.key等认证文件不支持相对路径,写测试用例时需注意。

func NewBaseClientSet() (*BaseClientSet, error) {
	data, err := AppFs.ReadFile(types.KUBE_CONF_FILE)
	if err != nil {
		return nil, err
	}
	config, err := clientcmd.RESTConfigFromKubeConfig(data)
	if err != nil {
		return nil, err
	}
	clientSet, err := kubernetes.NewForConfig(config)
	if err != nil {
		return nil, err
	}
	baseClient := &BaseClientSet{
		ClientSet: clientSet,
	}
	return baseClient, err
}

测试用例,动态获取绝对路径:

func TestNewBaseClientSet(t *testing.T) {
	Convey("Subject: Test pkg.restful.kube.client_set.NewBaseClientSet\n", t, func() {
		patches := NewPatches()
		defer patches.Reset()
		kubeConfigByte, _ := ioutil.ReadFile("../../../testdata/conf/kubectl.kubeconfig")
		_, filename, _, _ := runtime.Caller(0)
		absPath := path.Dir(filename)
		certificateAuthority := filepath.Join(absPath, "../../../testdata/ca.crt")
		clientCertificate := filepath.Join(absPath, "../../../testdata/kubectl.crt")
		clientKey := filepath.Join(absPath, "../../../testdata/kubectl.key")
		kubeConfig := fmt.Sprintf(string(kubeConfigByte), certificateAuthority, clientCertificate, clientKey)
		fmt.Println(kubeConfig)
		AppFs.WriteFile(types.KUBE_CONF_FILE, []byte(kubeConfig), 0640)
		Convey("BuildConfigFromFlags fail", func() {
			patches.ApplyFunc(clientcmd.BuildConfigFromFlags, func(string, string) (*rest.Config, error) {
				return &rest.Config{}, fmt.Errorf("BuildConfigFromFlags fail")
			})
			clientSet, err := NewBaseClientSet()
			So(err.Error(), ShouldContainSubstring, "fail")
			So(clientSet, ShouldEqual, nil)
		})
	})
 类似资料: