I am trying to get programmatically in Go, the namespace of the current-context from ~/.kube/config.
So far what I tried is from these modules:
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/kubernetes"
kubeconfig := filepath.Join(
os.Getenv("HOME"), ".kube", "config",
)
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Namespace: %s\n", config.Namespace())
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
But still no clue if clientset can give me the namespace I am looking for. From this thread: How to get current namespace of an in-cluster go Kubernetes client
It says something of this to be done: kubeconfig.Namespace()
import Required:
"k8s.io/client-go/tools/clientcmd"
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{} kubeConfig :=
clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules,
configOverrides)
namespace, _, err = kubeConfig.Namespace()
I found a solution using NewDefaultClientConfigLoadingRules
and then loading the rules. This works if your config is loadable with the default client config loading rules.
Example:
package main
import (
"github.com/davecgh/go-spew/spew"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
clientCfg, err := clientcmd.NewDefaultClientConfigLoadingRules().Load()
spew.Dump(clientCfg, err)
}
Gives you a https://godoc.org/k8s.io/client-go/tools/clientcmd/api#Config which contains the current context including its namespace.
Contexts: (map[string]*api.Context) (len=1) {
(string) (len=17) "xxx.xxxxx.xxx": (*api.Context)(0xc0001b2b40)({
LocationOfOrigin: (string) (len=30) "/path/to/.kube/config",
Cluster: (string) (len=17) "xxx.xxxxx.xxx",
AuthInfo: (string) (len=29) "xxxx@xxxx.com",
Namespace: (string) (len=7) "default",
Extensions: (map[string]runtime.Object) {
}
})
},
CurrentContext: (string) (len=17) "xxx.xxxxx.xxx",
For your information, ClientConfigLoadingRules
is a structure with different properties to tell the cliclient where to load the config from. The default one will use the path in your KUBECONFIG
environment variable in the Precedence
field.
(*clientcmd.ClientConfigLoadingRules)(0xc0000a31d0)({
ExplicitPath: (string) "",
Precedence: ([]string) (len=1 cap=1) {
(string) (len=30) "/path/to/.kube/config"
},
MigrationRules: (map[string]string) (len=1) {
(string) (len=30) "/path/to/.kube/config": (string) (len=35) "/path/to/.kube/.kubeconfig"
},
DoNotResolvePaths: (bool) false,
DefaultClientConfig: (clientcmd.ClientConfig) <nil>
})