From f324ac4d5cb6324266a77354bf3e765affd9c5bd Mon Sep 17 00:00:00 2001 From: Michael Burman Date: Tue, 23 Apr 2024 15:43:58 +0300 Subject: [PATCH] Add a method to extract restConfig for certain contextName in kubeconfig --- pkg/kubernetes/config.go | 34 ++++++++++++++++++++++++++++++++++ pkg/kubernetes/config_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 pkg/kubernetes/config.go create mode 100644 pkg/kubernetes/config_test.go diff --git a/pkg/kubernetes/config.go b/pkg/kubernetes/config.go new file mode 100644 index 0000000..76be017 --- /dev/null +++ b/pkg/kubernetes/config.go @@ -0,0 +1,34 @@ +package kubernetes + +import ( + "fmt" + + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" +) + +func LoadClientConfig(cfgFile, contextName string) (*rest.Config, error) { + config, err := clientcmd.LoadFromFile(cfgFile) + if err != nil { + return nil, err + } + + if contextName != "" { + if _, found := config.Contexts[contextName]; !found { + return nil, fmt.Errorf("context %s not found in kubeconfig file", contextName) + } + } + config.CurrentContext = contextName + + b, err := clientcmd.Write(*config) + if err != nil { + return nil, err + } + + clientConfig, err := clientcmd.NewClientConfigFromBytes(b) + if err != nil { + return nil, err + } + + return clientConfig.ClientConfig() +} diff --git a/pkg/kubernetes/config_test.go b/pkg/kubernetes/config_test.go new file mode 100644 index 0000000..ba1f44d --- /dev/null +++ b/pkg/kubernetes/config_test.go @@ -0,0 +1,26 @@ +package kubernetes + +import ( + "os/user" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestLoadConfigurationContext(t *testing.T) { + t.Skip("requires kind cluster with defaults to be running") + require := require.New(t) + + u, err := user.Current() + require.NoError(err) + cfgFile := filepath.Join(u.HomeDir, ".kube", "config") + + restConfig, err := LoadClientConfig(cfgFile, "kind-kind") + require.NoError(err) + + require.NotNil(restConfig.KeyData) + require.NotNil(restConfig.CertData) + require.True(strings.HasPrefix(restConfig.Host, "https://127.0.0.1")) +}