1. 程式人生 > >k8s叢集外go客戶端示例

k8s叢集外go客戶端示例

k8s叢集外go客戶端示例

(金慶的專欄 2018.7)

叢集內客戶端需要打包成docker映象,上傳映象,然後用 kubectl run 執行,
還要設定使用者角色,太麻煩,還是用叢集外客戶端測試比較方便。

客戶端庫使用 ericchiang/k8s, 比官方的 client-go 要簡單許多。

叢集內客戶端使用k8s.NewInClusterClient()建立,
叢集外客戶端使用 NewClient(config *Config), 需要輸入配置,
配置就是從 ~/.kube/config 讀取的。
參考 https://github.com/ericchiang/k8s/issues/79

程式碼如下:

package main

import (
    "context"
    "fmt"
    "log"
    "io/ioutil"

    "github.com/ghodss/yaml"
    "github.com/ericchiang/k8s"
    corev1 "github.com/ericchiang/k8s/apis/core/v1"
)

func main() {
    data, err := ioutil.ReadFile("config")
    if err != nil {
        panic(err)
    }

    // Unmarshal YAML into a Kubernetes config object.
var config k8s.Config if err := yaml.Unmarshal(data, &config); err != nil { panic(err) } client, err := k8s.NewClient(&config) // client, err := k8s.NewInClusterClient() if err != nil { log.Fatal(err) } var nodes corev1.NodeList if err := client.List(context.Background(), ""
, &nodes); err != nil { log.Fatal(err) } for _, node := range nodes.Items { fmt.Printf("name=%q schedulable=%t\n", *node.Metadata.Name, !*node.Spec.Unschedulable) } }

yaml 庫用了 ghodss/yaml,不能用 go-yaml, 不然報錯
yaml: unmarshal errors
見:https://github.com/ericchiang/k8s/issues/81

複製 .kube/config 到執行目錄,執行列出所有節點:

[jinqing@host-10-1-2-19 out-cluster]$ cp ~/.kube/config .
[jinqing@host-10-1-2-19 out-cluster]$ ./out-cluster 
name="host-10-1-2-20" schedulable=true
name="host-10-1-2-21" schedulable=true
name="host-10-1-2-22" schedulable=true
name="host-10-1-2-19" schedulable=true
name="host-10-1-2-18" schedulable=true