forked from TwiN/k8s-ttl-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
56 lines (52 loc) · 1.39 KB
/
client.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
package main
import (
"errors"
"os"
"path/filepath"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// CreateClients initializes a Kubernetes client and a dynamic client using either the kubeconfig file
// (if ENVIRONMENT is set to dev) or the in-cluster config otherwise.
func CreateClients() (kubernetes.Interface, dynamic.Interface, error) {
var cfg *rest.Config
if os.Getenv("ENVIRONMENT") == "dev" {
var kubeconfig string
if home := homeDir(); home != "" {
kubeconfig = filepath.Join(home, ".kube", "config")
} else {
return nil, nil, errors.New("home directory not found")
}
// use the current context in kubeconfig
clientConfig, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, nil, err
}
cfg = clientConfig
} else {
clientConfig, err := rest.InClusterConfig()
if err != nil {
return nil, nil, err
}
cfg = clientConfig
}
cfg.WarningHandler = rest.NoWarnings{}
cfg.UserAgent = "k8s-ttl-controller/1.0"
kubernetesClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, nil, err
}
dynamicClient, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, nil, err
}
return kubernetesClient, dynamicClient, nil
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}