-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a method to extract restConfig for certain contextName in kubeconfig
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) | ||
} |