How can I create a simple client app with the Kubernetes Go library?

前端 未结 3 824
梦毁少年i
梦毁少年i 2021-02-05 21:23

I\'m struggling with the Kubernetes Go library. The docs--at least the ones I found--appear out-of-date with the library itself. The example provided does not build because of

3条回答
  •  后悔当初
    2021-02-05 21:51

    With kubernetes go client, it could be done this way:

    package main
    
    import (
        "flag"
        "fmt"
    
        "k8s.io/client-go/kubernetes"
        "k8s.io/client-go/pkg/api/v1"
        "k8s.io/client-go/tools/clientcmd"
    )
    
    var (
        kubeconfig = flag.String("kubeconfig", "./config", "absolute path to the kubeconfig file")
    )
    
    func main() {
        flag.Parse()
        // uses the current context in kubeconfig
        config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
        if err != nil {
            panic(err.Error())
        }
        // creates the clientset
        clientset, err := kubernetes.NewForConfig(config)
        if err != nil {
            panic(err.Error())
        }
        services, err := clientset.Core().Services("").List(v1.ListOptions{})
        if err != nil {
            panic(err.Error())
        }
        fmt.Printf("There are %d pods in the cluster\n", len(services.Items))
    
        for _, s := range services.Items {
            for p, _ := range s.Spec.Ports {
                fmt.Println("Port:", s.Spec.Ports[p].Port)
                fmt.Println("NodePort:", s.Spec.Ports[p].NodePort)
            }
        }
    }
    

提交回复
热议问题