/
k8s_config.go
46 lines (39 loc) · 1.07 KB
/
k8s_config.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
package crd
import (
"log"
"os"
"path/filepath"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func getHomeDir() string {
if home := os.Getenv("HOME"); home != "" {
return home
}
return os.Getenv("USERPROFILE")
}
// NewKubernetesConfig tries to guess the current k8s configuration for the CRD
// plugin to use
func NewKubernetesConfig() (config *rest.Config, err error) {
// Try to use file-based config first
var kubeConfig string
if home := getHomeDir(); home != "" {
log.Printf("%s: Using home dir config...", PluginName)
kubeConfig = filepath.Join(home, ".kube", "config")
if _, ok := os.Stat(kubeConfig); ok == nil {
if config, err = clientcmd.BuildConfigFromFlags("", kubeConfig); err != nil {
return
}
} else {
log.Printf("%s: Skipping home dir config since %s does not exist", PluginName, kubeConfig)
}
}
// Otherwise try using in-cluster service account
if config == nil {
log.Printf("%s: Fetching cluster config...", PluginName)
if config, err = rest.InClusterConfig(); err != nil {
return
}
}
return config, err
}