You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package common
import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
// 存储已初始化好的 clientSet 变量
var clientSet *kubernetes.Clientset
// GetClientSet 单例的获取ClientSet的方法
// if clientSet == nil
// true: 未初始化初始化将其存储到clientSet变量中返回
// false: 已初始化,直接返回
func GetClientSet() (*kubernetes.Clientset, error) {
// 1. clientSet 是否已经初始化
// 已初始化
if clientSet != nil {
return clientSet, nil
}
// 未初始化,需要初始化
// 2. 配置 kubeconfig, 得到clientClientSet对象
// 配置文件位置
//kubeConfigPath := kubeConfigPath
// 构建配置,读取配置文件内容,解析为配置对象
config, err := clientcmd.BuildConfigFromFlags("", KubeConfigPath)
if err != nil {
return nil, err
}
// 3. 使用配置得到ClientSet对象
cs, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
// 4. 存储初始化好的ClientSet对象
clientSet = cs
// clientSet 初始化成功
return clientSet, nil
}