Skip to content

Commit

Permalink
Add a method to extract restConfig for certain contextName in kubeconfig
Browse files Browse the repository at this point in the history
  • Loading branch information
burmanm committed Apr 23, 2024
1 parent 0e1bf9a commit f324ac4
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
34 changes: 34 additions & 0 deletions pkg/kubernetes/config.go
Original file line number Diff line number Diff line change
@@ -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()
}
26 changes: 26 additions & 0 deletions pkg/kubernetes/config_test.go
Original file line number Diff line number Diff line change
@@ -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"))
}

0 comments on commit f324ac4

Please sign in to comment.