-
暮色呼如
所以经过一些实验和来自 k8s Slack 频道的提示,我有了这个例子。也许有人可以使用正确的导入路径更新示例。package mainimport ( "fmt" "log" "github.com/kubernetes/kubernetes/pkg/api" client "github.com/kubernetes/kubernetes/pkg/client/unversioned")func main() { config := client.Config{ Host: "http://my-kube-api-server.me:8080", } c, err := client.New(&config) if err != nil { log.Fatalln("Can't connect to Kubernetes API:", err) } s, err := c.Services(api.NamespaceDefault).Get("some-service-name") if err != nil { log.Fatalln("Can't get service:", err) } fmt.Println("Name:", s.Name) for p, _ := range s.Spec.Ports { fmt.Println("Port:", s.Spec.Ports[p].Port) fmt.Println("NodePort:", s.Spec.Ports[p].NodePort) }}
-
大话西游666
以下是如何使用最新的 Go 客户端执行此操作。如果您在 k8s 集群中:package mainimport ( "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())}如果您在集群之外:package mainimport ( "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("", <kube-config-path>) 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())}我在一篇博文中对此进行了更详细的介绍。
-
呼啦一阵风
使用 kubernetes go client,可以这样做:package mainimport ( "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) } }}