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.
46 lines
1.0 KiB
46 lines
1.0 KiB
package utils
|
|
|
|
import (
|
|
"errors"
|
|
"flag"
|
|
"k8s.io/client-go/rest"
|
|
"k8s.io/client-go/tools/clientcmd"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
/**
|
|
@author: sre
|
|
@date: 2022/8/10 0010
|
|
@desc: GetConfig from kubeConfigPath
|
|
**/
|
|
// GetConfig from kubeConfigPath
|
|
func GetConfig(kubeConfigPath ...string) (*rest.Config, error) {
|
|
var kubeConfig *string
|
|
|
|
if len(kubeConfigPath) > 0 {
|
|
kubeConfig = &kubeConfigPath[0]
|
|
} else if home := homeDir(); home != "" {
|
|
kubeConfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
|
|
} else {
|
|
log.Println("can not find kubeconfig")
|
|
return nil, errors.New("can not find kubeconfig")
|
|
}
|
|
// 加载配置文件,生成 config 对象
|
|
config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig)
|
|
if err != nil {
|
|
log.Println("加载配置文件失败: ", err.Error())
|
|
return nil, err
|
|
}
|
|
return config, nil
|
|
}
|
|
|
|
// homeDir get current user home
|
|
func homeDir() string {
|
|
if h := os.Getenv("HOME"); h != "" {
|
|
return h
|
|
}
|
|
return os.Getenv("USERPROFILE") // windows
|
|
}
|