zoukankan      html  css  js  c++  java
  • 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
    ", *node.Metadata.Name, !*node.Spec.Unschedulable)
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    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
  • 相关阅读:
    vue简介
    npm是什么
    杨辉三角(打印一个等腰、直角三角形)
    JS实现金额转换(将输入的阿拉伯数字)转换成中文
    Http请求处理流程
    FusionCharts的使用方法
    几种流行的AJAX框架对比:Jquery,Mootools,Dojo,ExtJs,Dwr
    Ubuntu 编译安装PHP
    Ubuntu/Deepin 添加桌面图标
    shell 脚本 ${1:-"false"}的含义
  • 原文地址:https://www.cnblogs.com/ExMan/p/13745398.html
Copyright © 2011-2022 走看看