diff --git a/pkg/k8sutil/client.go b/pkg/k8sutil/client.go index 73d6f2d5b..419a1ebb5 100644 --- a/pkg/k8sutil/client.go +++ b/pkg/k8sutil/client.go @@ -15,6 +15,8 @@ package k8sutil import ( + "fmt" + "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" "k8s.io/client-go/tools/clientcmd" @@ -35,3 +37,19 @@ func NewClientsetFromFile(kubeconfigPath string) (*kubernetes.Clientset, error) return apiclientset, nil } + +// NewClientset creates new Kubernetes Client set object from given kubeconfig +// file content. +func NewClientset(data []byte) (*kubernetes.Clientset, error) { + c, err := clientcmd.NewClientConfigFromBytes(data) + if err != nil { + return nil, fmt.Errorf("creating client config failed: %w", err) + } + + restConfig, err := c.ClientConfig() + if err != nil { + return nil, fmt.Errorf("converting client config to rest client config failed: %w", err) + } + + return kubernetes.NewForConfig(restConfig) +} diff --git a/pkg/k8sutil/client_test.go b/pkg/k8sutil/client_test.go new file mode 100644 index 000000000..134ad8ea6 --- /dev/null +++ b/pkg/k8sutil/client_test.go @@ -0,0 +1,54 @@ +// Copyright 2020 The Lokomotive 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 k8sutil_test + +import ( + "testing" + + "github.com/kinvolk/lokomotive/pkg/k8sutil" +) + +const ( + validKubeconfig = ` +apiVersion: v1 +kind: Config +clusters: +- name: admin + cluster: + server: https://nonexistent:6443 +users: +- name: admin + user: + token: "foo.bar" +current-context: admin +contexts: +- name: admin + context: + cluster: admin + user: admin +` +) + +func TestNewClientset(t *testing.T) { + if _, err := k8sutil.NewClientset([]byte(validKubeconfig)); err != nil { + t.Fatalf("Creating clientset from valid kubeconfig should succeed, got: %v", err) + } +} + +func TestNewClientsetInvalidKubeconfig(t *testing.T) { + if _, err := k8sutil.NewClientset([]byte("foo")); err == nil { + t.Fatalf("Creating clientset from invalid kubeconfig should fail") + } +}