client-go InClusterConfig方法

InClusterConfig方法

package main

import (
	"context"
	"test/signals"
	"time"
	"os"

	core_v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	klog "k8s.io/klog/v2"
)

func testInClusterConfig(stopCh <-chan struct{}) {
	// 除了手动设置kube-apiserver ip+port环境变量,还要手动设置/var/run/secrets/kubernetes.io/serviceaccount/token和ca.crt
	// 如果没有ca.crt,那么报错tls: failed to verify certificate: x509: certificate signed by unknown authority
	os.Setenv("KUBERNETES_SERVICE_HOST", "127.0.0.1")
	os.Setenv("KUBERNETES_SERVICE_PORT", "42929")

	cfg, err := rest.InClusterConfig()
	if err != nil {
		klog.Fatalf("Error building kubeconfig: %s", err.Error())
	}

	kubeClient, err := kubernetes.NewForConfig(cfg)
	if err != nil {
		klog.Fatalf("Error building kubernetes discoveryclient: %v", err)
	}

	ns := &core_v1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name: "test",
		},
	}
	if _, err := kubeClient.CoreV1().Namespaces().Create(context.Background(), ns, metav1.CreateOptions{}); err != nil {
		klog.Infof("create ns test failed, err is %v", err)
	} else {
		klog.Infof("create ns test success")
	}

	select {
	case <-stopCh:
		return
	case <-time.After(time.Hour):
	}
}

func main() {
	stopCh := signals.SetupSignalHandler()
	testInClusterConfig(stopCh)
}

tlsTransportCache的get方法
获取Client的transport,使用ServiceAccount时tlsConfig不会跳过证书认证,但是客户端只有根证书,只能完成与kube-apiserver的https单向认证,后面由token继续完成认证和鉴权。

 

posted on 2024-12-28 22:04  王景迁  阅读(1)  评论(0编辑  收藏  举报

导航