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

前端 未结 3 864
梦毁少年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 22:05

    Here's how to do it with the latest Go client.

    If you're inside the k8s cluster:

    package main
    
    import (
      "fmt"
    
      "k8s.io/client-go/1.5/kubernetes"
      "k8s.io/client-go/1.5/pkg/api/v1"
      "k8s.io/client-go/1.5/rest"
    )
    
    func main()  {
        config, err = rest.InClusterConfig()
        if err != nil {
          return nil, err
        }
    
        c, err := kubernetes.NewForConfig(config)
        if err != nil {
          return nil, err
        }
    
        // Get Pod by name
        pod, err := c.Pods(v1.NamespaceDefault).Get("my-pod")
        if err != nil {
            fmt.Println(err)
            return
        }
    
        // Print its creation time
        fmt.Println(pod.GetCreationTimestamp())
    }
    

    And if you're outside of the cluster:

    package main
    
    import (
      "fmt"
    
      "k8s.io/client-go/1.5/kubernetes"
      "k8s.io/client-go/1.5/pkg/api/v1"
      "k8s.io/client-go/1.5/tools/clientcmd"
    )
    
    func main()  {
        config, err := clientcmd.BuildConfigFromFlags("", )
        if err != nil {
          return nil, err
        }
    
        c, err := kubernetes.NewForConfig(config)
        if err != nil {
          return nil, err
        }
    
        // Get Pod by name
        pod, err := c.Pods(v1.NamespaceDefault).Get("my-pod")
        if err != nil {
            fmt.Println(err)
            return
        }
    
        // Print its creation time
        fmt.Println(pod.GetCreationTimestamp())
    }
    

    I have gone into more detail on this in a blog post.

提交回复
热议问题