Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge kubeconfig files for config #1883

Merged
merged 8 commits into from
Nov 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/context/update-kubeconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func UpdateKubeconfigCMD() *cobra.Command {
}

func ExecuteUpdateKubeconfig(ctx context.Context) error {
if err := kubeconfig.Write(okteto.Context().Cfg, config.GetKubeconfigPath()); err != nil {
if err := kubeconfig.Write(okteto.Context().Cfg, config.GetKubeconfigPath()[0]); err != nil {
return err
}
k8sContext := okteto.Context().Name
Expand Down
5 changes: 3 additions & 2 deletions integration/k8s-client.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ func K8sClient() (*kubernetes.Clientset, *rest.Config, error) {
return client, config, nil
}

func GetClientConfig(kubeconfigPath, kubeContext string) clientcmd.ClientConfig {
func GetClientConfig(kubeconfigPaths []string, kubeContext string) clientcmd.ClientConfig {

loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig
loadingRules.ExplicitPath = kubeconfigPath
loadingRules.Precedence = kubeconfigPaths

return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
loadingRules,
Expand Down
10 changes: 5 additions & 5 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,21 +220,21 @@ func homedirWindows() (string, error) {
}

// GetKubeconfigPath returns the path to the kubeconfig file, taking the KUBECONFIG env var into consideration
func GetKubeconfigPath() string {
func GetKubeconfigPath() []string {
home := GetUserHomeDir()
kubeconfig := filepath.Join(home, ".kube", "config")
kubeconfig := []string{filepath.Join(home, ".kube", "config")}
kubeconfigEnv := os.Getenv("KUBECONFIG")
if len(kubeconfigEnv) > 0 {
kubeconfig = splitKubeConfigEnv(kubeconfigEnv)
}
return kubeconfig
}

func splitKubeConfigEnv(value string) string {
func splitKubeConfigEnv(value string) []string {
if runtime.GOOS == "windows" {
return strings.Split(value, ";")[0]
return strings.Split(value, ";")
}
return strings.Split(value, ":")[0]
return strings.Split(value, ":")
}

func GetTokenPathDeprecated() string {
Expand Down
2 changes: 1 addition & 1 deletion pkg/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func IsForbidden(err error) bool {

// IsNotFound returns true if err is of the type not found
func IsNotFound(err error) bool {
return err != nil && (strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "doesn't exist")) || (strings.Contains(err.Error(), "not-found"))
return err != nil && (strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "doesn't exist") || strings.Contains(err.Error(), "not-found"))
}

// IsNotExist returns true if err is of the type does not exist
Expand Down
23 changes: 8 additions & 15 deletions pkg/k8s/kubeconfig/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ package kubeconfig

import (
"log"
"os"

"k8s.io/client-go/rest"

Expand All @@ -35,21 +34,15 @@ func Create() *clientcmdapi.Config {
}

//Get retrieves a kubeconfig file
func Get(kubeconfigPath string) *clientcmdapi.Config {
_, err := os.Stat(kubeconfigPath)
if err != nil {
if os.IsNotExist(err) {
return nil
}
log.Fatalf("error accessing your KUBECONFIG file '%s': %v", kubeconfigPath, err)
func Get(kubeconfigPaths []string) *clientcmdapi.Config {
loadingRules := clientcmd.ClientConfigLoadingRules{
Precedence: kubeconfigPaths,
}

cfg, err := clientcmd.LoadFromFile(kubeconfigPath)
mergedConfig, err := loadingRules.Load()
if err != nil {
log.Fatalf("error accessing your KUBECONFIG file '%s': %v", kubeconfigPath, err)
log.Fatalf("error accessing your KUBECONFIG file '%v': %v", kubeconfigPaths, err)
}

return cfg
return mergedConfig
}

//Write stores a kubeconfig file
Expand All @@ -58,7 +51,7 @@ func Write(cfg *clientcmdapi.Config, kubeconfigPath string) error {
}

// CurrentContext returns the name of the current context
func CurrentContext(kubeconfigPath string) string {
func CurrentContext(kubeconfigPath []string) string {
cfg := Get(kubeconfigPath)
if cfg == nil {
return ""
Expand All @@ -67,7 +60,7 @@ func CurrentContext(kubeconfigPath string) string {
}

// CurrentNamespace returns the name of the namespace in use by a given context
func CurrentNamespace(kubeconfigPath string) string {
func CurrentNamespace(kubeconfigPath []string) string {
cfg := Get(kubeconfigPath)
if cfg == nil {
return ""
Expand Down
151 changes: 151 additions & 0 deletions pkg/k8s/kubeconfig/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// Copyright 2021 The Okteto Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package kubeconfig

import (
"os"
"testing"

"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/runtime"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)

type kubeconfigFields struct {
Name []string
Namespace []string
CurrentContext string
}

func TestGetKubeconfig(t *testing.T) {
var tests = []struct {
name string
KubeconfigFields []kubeconfigFields
expected *clientcmdapi.Config
}{
{
name: "only one",
KubeconfigFields: []kubeconfigFields{
{
Name: []string{"test"},
Namespace: []string{"test"},
CurrentContext: "test",
},
},
expected: &clientcmdapi.Config{
Contexts: map[string]*clientcmdapi.Context{
"test": {
Namespace: "test",
Extensions: map[string]runtime.Object{},
},
},
CurrentContext: "test",
},
},
{
name: "two config files different contexts",
KubeconfigFields: []kubeconfigFields{
{
Name: []string{"test"},
Namespace: []string{"test"},
CurrentContext: "test",
},
{
Name: []string{"foo"},
Namespace: []string{"bar"},
CurrentContext: "foo",
},
},
expected: &clientcmdapi.Config{
Contexts: map[string]*clientcmdapi.Context{
"test": {
Namespace: "test",
Extensions: map[string]runtime.Object{},
},
"foo": {
Namespace: "bar",
Extensions: map[string]runtime.Object{},
},
},
CurrentContext: "test",
},
},
{
name: "two config files overlap contexts",
KubeconfigFields: []kubeconfigFields{
{
Name: []string{"test"},
Namespace: []string{"test"},
CurrentContext: "test",
},
{
Name: []string{"test"},
Namespace: []string{"namespace"},
CurrentContext: "test",
},
},
expected: &clientcmdapi.Config{
Contexts: map[string]*clientcmdapi.Context{
"test": {
Namespace: "namespace",
Extensions: map[string]runtime.Object{},
},
},
CurrentContext: "test",
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dirs := make([]string, 0)
for _, kubeconfig := range tt.KubeconfigFields {
dir, err := createKubeconfig(kubeconfig)
if err != nil {
t.Fatal(err)
}
dirs = append(dirs, dir)
defer os.Remove(dir)
}
config := Get(dirs)

for _, c := range config.Contexts {
c.LocationOfOrigin = ""
}

assert.Equal(t, config.Contexts, tt.expected.Contexts)
assert.Equal(t, config.CurrentContext, tt.expected.CurrentContext)
})
}
}

func createKubeconfig(kubeconfigFields kubeconfigFields) (string, error) {
dir, err := os.CreateTemp("", "")
if err != nil {
return "", err
}

contexts := make(map[string]*clientcmdapi.Context)
for idx := range kubeconfigFields.Name {
contexts[kubeconfigFields.Name[idx]] = &clientcmdapi.Context{Namespace: kubeconfigFields.Namespace[idx]}
}
cfg := &clientcmdapi.Config{
Contexts: contexts,
CurrentContext: kubeconfigFields.CurrentContext,
}
if err := Write(cfg, dir.Name()); err != nil {
return "", err
}
return dir.Name(), nil
}