kubernetes client-go 构建客户端的几种方式
package callk8s
import (
"context"
"log"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
type KConf struct {
Configure string
C *kubernetes.Clientset
NameSpace string
}
// NewCli 从指定配置文件中加载配置
func NewCli(confDir, namespace string) (*KConf, error) {
var kconf KConf
kconf.Configure = confDir
kconf.NameSpace = namespace
config, err := clientcmd.BuildConfigFromFlags("", kconf.Configure)
if err != nil {
log.Println(err)
return &kconf, err
}
c, err := kubernetes.NewForConfig(config)
if err != nil {
log.Println(err)
return &kconf, err
}
kconf.C = c
return &kconf, nil
}
// NewFromBytes 从二进制内存中加载配置
func NewFromBytes(configBytes []byte, namespace string) (*KConf, error) {
var kconf KConf
nccfb, err := clientcmd.NewClientConfigFromBytes(configBytes)
if err != nil {
log.Println("Err: ", err)
return &kconf, err
}
tmpf, err := nccfb.ClientConfig()
if err != nil {
log.Println("Err: ", err)
return &kconf, err
}
kconf.C, err = kubernetes.NewForConfig(tmpf)
if err != nil {
log.Println("Err: ", err)
return &kconf, err
}
return &kconf, nil
}
// RestClientFromSA 从pod sa 中获取 ,/var/run/secerts/kubernetes.io/serviceaccount/token
func RestClientFromSA() (*KConf, error) {
var kconf KConf
config, err := rest.InClusterConfig()
if err != nil {
log.Printf("Err: %v", err)
return &kconf, err
}
kconf.C, err = kubernetes.NewForConfig(config)
if err != nil {
return &kconf, err
}
return &kconf, nil
}
标签:return,nil,err,kubernetes,client,go,k8s,kconf,log
From: https://www.cnblogs.com/shangmo/p/17979720