-
Notifications
You must be signed in to change notification settings - Fork 151
/
custom_kubeconfig_helpers.go
62 lines (52 loc) · 1.48 KB
/
custom_kubeconfig_helpers.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
package k8s
import (
"context"
"os"
"path"
"runtime"
"strings"
"github.com/ghodss/yaml"
api "github.com/kubernetes-client/go-base/config/api"
"github.com/scaleway/scaleway-cli/v2/internal/core"
)
// get the path to the wanted kubeconfig on disk
// either the file pointed by the KUBECONFIG env variable (first one in case of a list)
// or the $HOME/.kube/config
func getKubeconfigPath(ctx context.Context) (string, error) {
var kubeconfigPath string
kubeconfigEnv := core.ExtractEnv(ctx, "KUBECONFIG")
if kubeconfigEnv != "" {
if runtime.GOOS == "windows" {
kubeconfigPath = strings.Split(kubeconfigEnv, ";")[0] // list is separated by ; on windows
} else {
kubeconfigPath = strings.Split(kubeconfigEnv, ":")[0] // list is separated by : on linux/macos
}
} else {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
kubeconfigPath = path.Join(homeDir, kubeLocationDir, "config")
}
return kubeconfigPath, nil
}
func openAndUnmarshalKubeconfig(kubeconfigPath string) (*api.Config, error) {
// getting the existing file
file, err := os.ReadFile(kubeconfigPath)
if err != nil {
return nil, err
}
var kubeconfig api.Config
err = yaml.Unmarshal(file, &kubeconfig)
if err != nil {
return nil, err
}
return &kubeconfig, nil
}
func marshalAndWriteKubeconfig(kubeconfig *api.Config, kubeconfigPath string) error {
newKubeconfig, err := yaml.Marshal(*kubeconfig)
if err != nil {
return err
}
return os.WriteFile(kubeconfigPath, newKubeconfig, 0600)
}