forked from k8s-club/k8s-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_set.go
83 lines (68 loc) · 1.79 KB
/
client_set.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package client
import (
"flag"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"log"
"os"
"path/filepath"
)
// 配置文件
func K8sRestConfig() *rest.Config {
//// 需要注意这里的config文件目录。
//config, err := clientcmd.BuildConfigFromFlags("", "config")
//if err != nil {
// log.Fatal(err)
//}
var kubeConfig *string
if home := HomeDir(); home != "" {
kubeConfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "")
} else {
kubeConfig = flag.String("kubeconfig", "", "")
}
//flag.Parse()
// 首先使用 inCluster 模式(需要去配置对应的 RBAC 权限,默认的sa是default->是没有获取deployments的List权限)
var config *rest.Config
config, err := rest.InClusterConfig()
if err != nil {
// 使用 KubeConfig 文件创建集群配置 Config 对象
if config, err = clientcmd.BuildConfigFromFlags("", *kubeConfig); err != nil {
log.Fatal(err)
}
}
return config
}
// 返回初始化k8s-client
func InitClient(config *rest.Config) kubernetes.Interface {
c, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
return c
}
// 返回初始化k8s-dynamic-client
func InitDynamicClient(config *rest.Config) dynamic.Interface {
c, err := dynamic.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
return c
}
func HomeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE")
}
var ClientSet = &Client{}
type Client struct {
Client kubernetes.Interface // 因为需要单元测试,所以不要用 *kubernetes.Clientset
DynamicClient dynamic.Interface
}
func init() {
config := K8sRestConfig()
ClientSet.Client = InitClient(config)
ClientSet.DynamicClient = InitDynamicClient(config)
}