登录
首页 >  Golang >  Go问答

如何在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学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>