How to get current k8s context name using client-go

huangapple go评论83阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年1月28日 04:05:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/70885022.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定