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
  • 相关阅读:
    如何在win7下安装python包工具pip
    史上最易懂的Android jni开发资料--NDK环境搭建
    转——Nginx+keepalived实现负载均衡和高可用性 in ubuntu
    nodejs优化
    mysql linux 备份脚本
    转 分页代码
    仿微信界面
    (转载)Android 如何让service 不被杀死 && service 开机自动启动
    Python模块 Socket
    批处理中的多种注释方法
  • 原文地址:https://www.cnblogs.com/ExMan/p/13745398.html
Copyright © 2011-2022 走看看