From 59ef6279f366f2012ad64cd3f5a8ac0fe34eea58 Mon Sep 17 00:00:00 2001 From: lonelyCZ Date: Wed, 29 Mar 2023 10:53:46 +0800 Subject: [PATCH] Support to run karmadactl init within a pod Signed-off-by: lonelyCZ --- pkg/karmadactl/util/apiclient/apiclient.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pkg/karmadactl/util/apiclient/apiclient.go b/pkg/karmadactl/util/apiclient/apiclient.go index f99071450..40106cfe2 100644 --- a/pkg/karmadactl/util/apiclient/apiclient.go +++ b/pkg/karmadactl/util/apiclient/apiclient.go @@ -1,6 +1,7 @@ package apiclient import ( + "fmt" "os" "path/filepath" @@ -43,6 +44,17 @@ func RestConfig(context, kubeconfigPath string) (*rest.Config, error) { kubeconfigPath = env.GetString("KUBECONFIG", defaultKubeConfig) } if !Exists(kubeconfigPath) { + // Given no kubeconfig is provided, give it a try to load the config by + // in-cluster mode if the client running inside a pod running on kubernetes. + host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT") + if len(host) > 0 || len(port) > 0 { // in-cluster mode + inClusterRestConfig, err := rest.InClusterConfig() + if err != nil { + return nil, fmt.Errorf("failed to load rest config by in-cluster mode: %v", err) + } + return inClusterRestConfig, nil + } + return nil, ErrEmptyConfig }