【问题标题】:Accessing AKS kubeconfig file from go program从 go 程序访问 AKS kubeconfig 文件
【发布时间】:2020-12-17 02:25:00
【问题描述】:

我正在尝试编写一个 Go 程序来从集群中获取 pod 日志。我正在使用 AKS kubernetes 集群。如何访问脚本中的 kubeconfig 文件?以下是我的代码:

package main

import (
    "context"
    "flag"
    "fmt"
    "time"
    "os"
    "path/filepath"

    "k8s.io/apimachinery/pkg/api/errors"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    //"k8s.io/client-go/rest"
    "k8s.io/client-go/tools/clientcmd"
    //
    // Uncomment to load all auth plugins
    // _ "k8s.io/client-go/plugin/pkg/client/auth"
    //
    // Or uncomment to load specific auth plugins
    // _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
    // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
    // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
    // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)

func main() {
    /*// creates the in-cluster config
    config, err := rest.InClusterConfig()
    if err != nil {
        panic(err.Error())
    }*/
    
    fmt.Printf("Creating cluster config")
    
    kubePtr := flag.Bool("use-kubeconfig", false, "use kubeconfig on local system")
    flag.Parse()
    
    fmt.Printf("Updating the existing config")

    var kubeconfig string

    if *kubePtr == true {
        kubeconfig = filepath.Join(os.Getenv("HOME"), ".kube", "config")
    } else {
        kubeconfig = ""
    }
    
    fmt.Printf("Building config from flags")

    config, err := clientcmd.BuildConfigFromKubeconfigGetter("", kubeconfig)
    
    fmt.Printf("creating the clientset")
    
    
    // creates the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }
    for {
        // get pods in all the namespaces by omitting namespace
        // Or specify namespace to get pods in particular namespace
        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 e.g. errors.IsNotFound()
        // - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
        _, err = clientset.CoreV1().Pods("default").Get(context.TODO(), "example-xxxxx", metav1.GetOptions{})
        if errors.IsNotFound(err) {
            fmt.Printf("Pod example-xxxxx not found in default namespace\n")
        } else if statusError, isStatus := err.(*errors.StatusError); isStatus {
            fmt.Printf("Error getting pod %v\n", statusError.ErrStatus.Message)
        } else if err != nil {
            panic(err.Error())
        } else {
            fmt.Printf("Found example-xxxxx pod in default namespace\n")
        }

        time.Sleep(10 * time.Second)
    }
}

我在第 51 行遇到错误。以下是我的错误:

error creating inClusterConfig, falling back to default config: unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined

在哪里可以找到KUBERNETES_SERVICE_HOSTKUBERNETES_SERVICE_PORT 以及如何通过?我找不到任何例子。

【问题讨论】:

  • 配置文件在$HOME/.kube/config?你的操作系统是什么?
  • 你是用-use-kubeconfig=true开始的吗? KUBERNETES_SERVICE_HOST 和 KUBERNETES_SERVICE_PORT 是在 k8s pod 中运行时自动注入容器的环境变量。在本地运行时不要使用它。
  • @ArghyaSadhu 我如何在 go 程序中访问该文件?
  • @Matt 我在哪里添加 -use-kubeconfig=true?在程序中或当我从命令提示符调用程序时?很抱歉提出愚蠢的问题,我对此很陌生。
  • 试试 go run main.go -use-kubeconfig=true @SormitaChakraborty 你创建了一个默认为 false 的标志。当 flag 设置为 true 时,它​​将 kubeconfig 变量设置为 kubeconfig 路径。但因为它是假的,所以它设置为“”,这就是它找不到配置的原因。但这只是我的猜测。请尝试一下,如果解决了,请告诉我。

标签: go kubernetes azure-aks kubeconfig


【解决方案1】:

从示例here 中,代码应如下所示。注意使用BuildConfigFromFlags 函数加载kubeconfig 文件。

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()

    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err)
    }
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err)
    }
    ...

确保~/.kube/config 处存在有效的 kubeconfig 文件 地点。在 AKS 上,您可以运行以下命令来获取 kubeconfig 文件,该文件将文件放在 ~/.kube/config

az aks get-credentials --resource-group myResourceGroup --name myAKSCluster

【讨论】:

    【解决方案2】:

    我注意到的第一件事是你没有提到你是如何开始你的程序的。

    查看我看到的代码,您正在创建一个默认为falsekubePtr 标志。 当 flag 设置为 true 时,它会将 kubeconfig 变量设置为 kubeconfig 路径,但是因为它是 false(默认情况下)它会将其设置为 "",这就是它找不到配置的原因。


    将此标志设置为 true 后,您会看到以下错误:

    不能在 clientcmd.BuildConfigFromKubeconfigGetter 的参数中使用 kubeconfig(类型字符串)作为类型 clientcmd.KubeconfigGetter

    whihc 表示您的类型不匹配。 让我们看看BuildConfigFromKubeconfigGetter() function 参数类型:

    func BuildConfigFromKubeconfigGetter(masterUrl string, kubeconfigGetter KubeconfigGetter) (*restclient.Config, error)
    

    请注意,您将 string 作为参数传递,该参数的类型应为 KubeconfigGetter

    最好使用不同的函数,如 clientcmd.BuildConfigFromFlags(),作为参数,期望 kubeconfig 文件的路径(字符串)。

    在 github 上的官方 client-go 库存储库中,您可以找到 several examples,它可以帮助您开始使用 clien-go 库。

    例如查看this official example,注意客户端是如何配置的。

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 2021-03-20
      • 2022-07-06
      • 2023-01-17
      • 2013-05-26
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      相关资源
      最近更新 更多