Skip to content

Commit

Permalink
Merge pull request #7 from utkarsh-pro/utkarsh-pro/feature/detect_kub…
Browse files Browse the repository at this point in the history
…econfig

Add DetectKubeConfig and createNamespaceIfNotExist functions
  • Loading branch information
kumarabd authored Nov 22, 2020
2 parents ca4beb9 + 39d24f7 commit cdcfda1
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
20 changes: 19 additions & 1 deletion utils/kubernetes/apply-manifest.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package kubernetes

import (
kubeerror "k8s.io/apimachinery/pkg/api/errors"
"context"
"strings"

v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
kubeerror "k8s.io/apimachinery/pkg/api/errors"
meta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
Expand Down Expand Up @@ -53,6 +57,10 @@ func (client *Client) ApplyManifest(contents []byte, options ApplyOptions) error
options.Namespace = val
}

if err = createNamespaceIfNotExist(client.Clientset, context.TODO(), options.Namespace); err != nil {
return ErrApplyManifest(err)
}

if options.Delete {
_, err = deleteObject(helper, options.Namespace, object)
if err != nil {
Expand Down Expand Up @@ -118,3 +126,13 @@ func deleteObject(restHelper *resource.Helper, namespace string, obj runtime.Obj
}
return restHelper.Delete(namespace, name)
}

func createNamespaceIfNotExist(kubeClientset kubernetes.Interface, ctx context.Context, namespace string) error {
nsSpec := &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}
_, err := kubeClientset.CoreV1().Namespaces().Create(ctx, nsSpec, metav1.CreateOptions{})
if !errors.IsAlreadyExists(err) {
return err
}

return nil
}
34 changes: 34 additions & 0 deletions utils/kubernetes/detect-kubeconfig.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package kubernetes

import (
"os"
"path"

"github.com/layer5io/meshkit/utils"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)

// DetectKubeConfig detects the kubeconfig for the kubernetes cluster and returns it
func DetectKubeConfig() (config *rest.Config, err error) {
// If deployed within the cluster
if config, err = rest.InClusterConfig(); err == nil {
return config, err
}

// Look for kubeconfig from the path mentioned in $KUBECONFIG
kubeconfig := os.Getenv("KUBECONFIG")
if kubeconfig != "" {
if config, err = clientcmd.BuildConfigFromFlags("", kubeconfig); err == nil {
return config, err
}
}

// Look for kubeconfig at the default path
path := path.Join(utils.GetHome(), ".kube", "config")
if config, err = clientcmd.BuildConfigFromFlags("", path); err == nil {
return config, err
}

return
}

0 comments on commit cdcfda1

Please sign in to comment.