| gio | f6ad298 | 2024-08-23 17:42:49 +0400 | [diff] [blame] | 1 | package kube |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "k8s.io/apimachinery/pkg/runtime/schema" |
| 7 | "k8s.io/client-go/kubernetes" |
| 8 | "k8s.io/client-go/rest" |
| 9 | "k8s.io/client-go/tools/clientcmd" |
| 10 | clientcmdapi "k8s.io/client-go/tools/clientcmd/api" |
| 11 | clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest" |
| 12 | ) |
| 13 | |
| 14 | type KubeConfigOpts struct { |
| 15 | KubeConfig string |
| 16 | KubeConfigPath string |
| 17 | } |
| 18 | |
| 19 | func NewKubeClient(opts KubeConfigOpts) (*kubernetes.Clientset, error) { |
| 20 | if opts.KubeConfig != "" && opts.KubeConfigPath != "" { |
| 21 | return nil, fmt.Errorf("both path and config can not be defined") |
| 22 | } |
| 23 | if opts.KubeConfig != "" { |
| 24 | var cfg clientcmdapi.Config |
| 25 | decoded, _, err := clientcmdlatest.Codec.Decode([]byte(opts.KubeConfig), &schema.GroupVersionKind{Version: clientcmdlatest.Version, Kind: "Config"}, &cfg) |
| 26 | if err != nil { |
| 27 | return nil, err |
| 28 | } |
| 29 | getter := func() (*clientcmdapi.Config, error) { |
| 30 | return decoded.(*clientcmdapi.Config), nil |
| 31 | } |
| 32 | config, err := clientcmd.BuildConfigFromKubeconfigGetter("", getter) |
| 33 | if err != nil { |
| 34 | return nil, err |
| 35 | } |
| 36 | return kubernetes.NewForConfig(config) |
| 37 | } |
| 38 | if opts.KubeConfigPath == "" { |
| 39 | config, err := rest.InClusterConfig() |
| 40 | if err != nil { |
| 41 | return nil, err |
| 42 | } |
| 43 | return kubernetes.NewForConfig(config) |
| 44 | } else { |
| 45 | config, err := clientcmd.BuildConfigFromFlags("", opts.KubeConfigPath) |
| 46 | if err != nil { |
| 47 | return nil, err |
| 48 | } |
| 49 | return kubernetes.NewForConfig(config) |
| 50 | } |
| 51 | } |