Use in-cluster config when kubeconfig file is not found (#2996)

* Use in-cluster config if KUBECONFIG env is not set.
Or when kubeconfig file is not found in user's home directory.
* Fixed e2e cli tests failure
* Resolve review comments
* Join kubeconfig not found and failed to load in-cluster config errors


---------

Signed-off-by: Md Soharab Ansari <soharab.ansari@infracloud.io>
This commit is contained in:
soharab-ic
2024-08-24 09:01:27 +05:30
committed by GitHub
parent 26f964886e
commit bf19e2fae2
+43 -12
View File
@@ -22,6 +22,7 @@ import (
"os"
"os/user"
"path/filepath"
"strings"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
@@ -99,32 +100,44 @@ func GetClientConfig(kubeContext string) (clientcmd.ClientConfig, error) {
func NewClient(opts ClientOptions) (*Client, error) {
client := &Client{}
var err error
var err1 error
var cmdConfig clientcmd.ClientConfig
if len(opts.Namespace) > 0 {
client.Namespace = opts.Namespace
} else {
cmdConfig, err = GetClientConfig(opts.KubeContext)
if err != nil {
return nil, err
cmdConfig, err1 = GetClientConfig(opts.KubeContext)
if err1 != nil {
console.Verbose(2, err1.Error())
}
namespace, _, err := cmdConfig.Namespace()
if err != nil {
return nil, err
}
client.Namespace = namespace
}
console.Verbose(2, "Kubeconfig default namespace %q", client.Namespace)
if cmdConfig != nil {
namespace, _, err := cmdConfig.Namespace()
if err != nil {
return nil, err
}
client.Namespace = namespace
console.Verbose(2, "Kubeconfig default namespace %q", namespace)
}
}
if opts.RestConfig != nil {
client.RestConfig = opts.RestConfig
} else {
} else if cmdConfig != nil {
restConfig, err := cmdConfig.ClientConfig()
if err != nil {
return nil, err
}
client.RestConfig = restConfig
} else {
console.Verbose(2, "Using in-cluster config")
restConfig, err2 := rest.InClusterConfig()
if err2 != nil {
return nil, errors.Join(err1, err2)
}
client.RestConfig = restConfig
client.Namespace = getInClusterConfigNamespace()
console.Verbose(2, "In-cluster config default namespace %q", client.Namespace)
}
clientGen := crd.NewClientGeneratorWithRestConfig(client.RestConfig)
@@ -142,3 +155,21 @@ func NewClient(opts ClientOptions) (*Client, error) {
return client, nil
}
// Fetch default namespace for inClusterConfig
func getInClusterConfigNamespace() string {
// This way assumes you've set the POD_NAMESPACE environment variable using the downward API.
// This check has to be done first for backwards compatibility with the way InClusterConfig was originally set up
if ns, ok := os.LookupEnv("POD_NAMESPACE"); ok {
return ns
}
// Fall back to the namespace associated with the service account token, if available
if data, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil {
if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
return ns
}
}
return "default"
}