英文:
How to get current k8s context name using client-go
问题
我正在尝试使用client-go从~/.kube/config中获取/打印当前kubernetes上下文的名称。
我已经成功进行了身份验证并获取了*rest.Config对象。
config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig},
&clientcmd.ConfigOverrides{
CurrentContext: "",
}).ClientConfig()
但是我在config结构体中没有看到任何相关的字段。
请注意,尽管我在ConfigOverrides中传递了一个空字符串(""),但返回的config对象提供了一个基于当前kubectl上下文的kubernetes.Clientset。
英文:
I am trying to get / print the name of my current kubernetes context as it is configured in ~/.kube/config using client-go
I hava managed to authenticate and get the *rest.Config object
config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig},
&clientcmd.ConfigOverrides{
CurrentContext: "",
}).ClientConfig()
but I don't see any relevant fields in the config struct.
Note that despite the fact I am passing an empty string ("") in the ConfigOverrides the config object returned provides me a kubernetes.Clientset that is based on my current kubectl context.
答案1
得分: 9
ClientConfig()函数返回Kubernetes API客户端配置,因此它没有关于您的配置文件的信息。
要获取当前上下文,您需要调用RawConfig(),然后有一个名为CurrentContext的字段。
以下代码应该可以工作。
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig},
&clientcmd.ConfigOverrides{
CurrentContext: "",
}).RawConfig()
currentContext := config.CurrentContext
英文:
The function ClientConfig() returns the Kubernetes API client config, so it has no information about your config file.
To get the current context, you need to call RawConfig(), then there is a field called CurrentContext.
The following code should work.
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig},
&clientcmd.ConfigOverrides{
CurrentContext: "",
}).RawConfig()
currentContext := config.CurrentContext
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论