如何在Kubernetes集群外部获取当前命名空间的Go客户端?
来源:stackoverflow
时间:2024-02-08 17:03:23 369浏览 收藏
哈喽!今天心血来潮给大家带来了《如何在Kubernetes集群外部获取当前命名空间的Go客户端?》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
如何使用 client-go 库获取集群外 go kubernetes 客户端的当前命名空间?
我正在使用以下代码示例:https://github.com/kubernetes/client-go/blob/master/examples/out-of-cluster-client-configuration/main.go 作为集群外客户端。
这是我的 kubeconfig 的摘录,可能有助于澄清:
- context: cluster: kind-kind namespace: mynamespace user: kind-kind name: kind-kind current-context: kind-kind
我想找到一种简单的方法来检索 mynamespace
。
正确答案
感谢 @rick-rackow 的回答和评论,我能够提高对 kubeconfig api 的理解,所以这里有一个适合我的简单解决方案:
package main import ( "flag" "fmt" "path/filepath" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" ) func main() { var kubeconfig *string if home := homedir.homedir(); home != "" { kubeconfig = flag.string("kubeconfig", filepath.join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") } else { kubeconfig = flag.string("kubeconfig", "", "absolute path to the kubeconfig file") } flag.parse() ns := getcurrentnamespace(*kubeconfig) fmt.printf("namespace: %s", ns) } // get the default namespace specified in the kubeconfig file current context func getcurrentnamespace(kubeconfig string) string { config, err := clientcmd.loadfromfile(kubeconfig) if err != nil { panic(err.error()) } ns := config.contexts[config.currentcontext].namespace if len(ns) == 0 { ns = "default" } return ns }
不存在“当前命名空间”这样的东西。
所有命名空间同时存在,您可以同时访问它们。 “当前命名空间”的想法主要来自于附加插件,例如 kubens。现实情况是,它只是给定集群的 kube 上下文的详细信息,如 here 中所述,您可以在其中指定访问给定命名空间的一组凭证/用户组合。如果您根本不指定命名空间,则还有通过 kubectl
执行命令的默认命名空间,如您可以阅读的 in the documentation 所示。因此,config
类型的对象也没有能力保存有关该信息的任何信息。阅读here
使用 kubens
等工具,您可以“保留”默认要针对哪个名称空间执行命令,您可以获得一些额外的选项,但它们仍然需要存储该状态,它们在每个集群的状态文件中执行此操作,例如 .kube/kubens/test
。
在您发布的代码示例中,您还可以看到命名空间实际上是通过变量 namespace
指定的,该变量设置为 default
here
您也可以尝试通过标志指定名称空间,例如
func main() { var kubeconfig *string var namespace *string if home := homedir.homedir(); home != "" { kubeconfig = flag.string("kubeconfig", filepath.join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") } else { kubeconfig = flag.string("kubeconfig", "", "absolute path to the kubeconfig file") } namespace = flag.string("namespace", "default", "namespace to execute commands against") flag.parse() // use the current context in kubeconfig config, err := clientcmd.buildconfigfromflags("", *kubeconfig) if err != nil { panic(err.error()) } // create the clientset clientset, err := kubernetes.newforconfig(config) if err != nil { panic(err.error()) } for { pods, err := clientset.corev1().pods("").list(context.todo(), metav1.listoptions{}) if err != nil { panic(err.error()) } fmt.printf("there are %d pods in the cluster\n", len(pods.items)) // examples for error handling: // - use helper functions like e.g. errors.isnotfound() // - and/or cast to statuserror and use its properties like e.g. errstatus.message pod := "example-xxxxx" _, err = clientset.corev1().pods(*namespace).get(context.todo(), pod, metav1.getoptions{}) if errors.isnotfound(err) { fmt.printf("pod %s in namespace %s not found\n", pod, *namespace) } else if statuserror, isstatus := err.(*errors.statuserror); isstatus { fmt.printf("error getting pod %s in namespace %s: %v\n", pod, *namespace, statuserror.errstatus.message) } else if err != nil { panic(err.error()) } else { fmt.printf("found pod %s in namespace %s\n", pod, *namespace) } time.sleep(10 * time.second) } }
如果你想复制类似的行为,就像 kubens 所做的那样,你可以将命名空间存储在一个文件中,并从那里读取它,如果没有其他内容作为标志传递,如果文件不存在,则切换到 default
,即您从未访问过集群:
func main() { var kubeconfig *string var namespace *string if home := homedir.HomeDir(); home != "" { kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") } else { kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file") } namespace = flag.String("namespace", "", "namespace to execute commands against") flag.Parse() // use the current context in kubeconfig config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) if err != nil { panic(err.Error()) } // create the clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } // write to file if namespace is given as flag if *namespace != "" { dat := []byte(*namespace) err := os.WriteFile(config.ServerName, dat, 0644) if err != nil { panic(err.Error()) } } // read from file if namespace is not given as flag, otherwise use default if *namespace == "" { _, doesNotExist := os.Stat(config.ServerName) if doesNotExist == nil { dat, err := os.ReadFile(config.ServerName) if err != nil { panic(err.Error()) } *namespace = string(dat) } if doesNotExist != nil { *namespace = "default" } }
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何在Kubernetes集群外部获取当前命名空间的Go客户端?》文章吧,也可关注golang学习网公众号了解相关技术文章。
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习