/
kubeconfig.go
46 lines (39 loc) · 1.02 KB
/
kubeconfig.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 kube
import (
"fmt"
"os"
"os/user"
"path/filepath"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
)
func getClusterFromKubeconfig() (string, error) {
config, err := ReadKubeconfig()
if err != nil {
return "", err
}
// Getting the current context
currentContext := config.CurrentContext
context := config.Contexts[currentContext]
return context.Cluster, nil
}
func ReadKubeconfig() (api.Config, error) {
// Check if KUBECONFIG environment variable is set
kubeconfigPath := os.Getenv("KUBECONFIG")
// If KUBECONFIG is not set, use the default path
if kubeconfigPath == "" {
usr, err := user.Current()
if err != nil {
fmt.Printf("Failed to get user information: %v\n", err)
return api.Config{}, err
}
kubeconfigPath = filepath.Join(usr.HomeDir, ".kube", "config")
}
// Loading the kubeconfig file
config, err := clientcmd.LoadFromFile(kubeconfigPath)
if err != nil {
fmt.Printf("Failed to load kubeconfig: %v\n", err)
return api.Config{}, err
}
return *config, nil
}