下载地址: https://github.com/kubernetes/client-go

官方使用文档参考:https://v1-16.docs.kubernetes.io/docs/reference/using-api/client-libraries/

安装,使用的为kubernetes1.15.6版本的kubernetes集群

go get -u -v k8s.io/client-go@kubernetes-1.15.6

在操作外部k8s集群示例

创建一个clientSet

package main

import (
"flag"
"fmt"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
appv1 "k8s.io/api/apps/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
) func main() { var (
k8sconfig = flag.String("k8sconfig", "./admin.conf", "kubernetes auth config") //使用kubeconfig配置文件进行集群权限认证
config *rest.Config
err error
)
flag.Parse() config, err = clientcmd.BuildConfigFromFlags("", *k8sconfig)
if err != nil {
fmt.Println(err)
return
}
// 从指定的config创建一个新的clientset
clientset, err := kubernetes.NewForConfig(config) if err != nil {
fmt.Println(err)
return
} else {
fmt.Println("connect kubernetes cluster success.")
}

获取指定namespace中的pod信息

// 获取pod列表 pod为名称空间级别资源需指定名称空间
pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{}) if err != nil {
panic(err)
}
// 循环打印pod的信息
for _,pod := range pods.Items {
fmt.Println(pod.ObjectMeta.Name,pod.Status.Phase)
}

创建namespace

nsClient := clientset.CoreV1().Namespaces()

ns := &apiv1.Namespace{
ObjectMeta:metav1.ObjectMeta{
Name: "testzhangsan",
},
Status:apiv1.NamespaceStatus{
Phase:apiv1.NamespaceActive,
},
}
ns,err = nsClient.Create(ns) if err != nil{
panic(err)
} fmt.Println(ns.ObjectMeta.Name,ns.Status.Phase)

获取指定名称空间下svc信息

svclist,err := clientset.CoreV1().Services("kube-system").List(metav1.ListOptions{})

for _,svc := range svclist.Items {
fmt.Println(svc.Name,svc.Spec.ClusterIP,svc.Spec.Ports)
}

创建一个deployment控制器

kubernetes中控制器的资源清单如下列所示,故需要按照资源清单的示例来根据客户端库创建控制器

apiVersion: v1
kind: Pod
metadata:
name: test-pod
namespace: default
labels:
app: redis
spec:
containers:
- name: redis-app
image: redis
imagePullPolicy: IfNotPresent
ports:
- name: redis
containerPort: 6379
- name: busybox
image: busybox
command:
- "/bin/sh"
- "-c"
- "sleep 3600"

deployment控制器格式是如下结构体,需要根据此结构体创建

// Deployment enables declarative updates for Pods and ReplicaSets.
type Deployment struct {
metav1.TypeMeta `json:",inline"`
// Standard object metadata.
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the Deployment.
// +optional
Spec DeploymentSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the Deployment.
// +optional
Status DeploymentStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

需要metadata和spec两个选项

故需创建两个结构体,metadate只需要简单的名称和标签定义即可

ObjectMeta:metav1.ObjectMeta{
Name: "testgolangclient",
},

spec为pod的属性定义和副本数量等信息。一个完整的deployment控制器的结构体格式如下

type DeploymentSpec struct {
// Number of desired pods. This is a pointer to distinguish between explicit
// zero and not specified. Defaults to 1.
// +optional
Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` // Label selector for pods. Existing ReplicaSets whose pods are
// selected by this will be the ones affected by this deployment.
// It must match the pod template's labels.
Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,2,opt,name=selector"` // Template describes the pods that will be created.
Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"` // The deployment strategy to use to replace existing pods with new ones.
// +optional
// +patchStrategy=retainKeys
Strategy DeploymentStrategy `json:"strategy,omitempty" patchStrategy:"retainKeys" protobuf:"bytes,4,opt,name=strategy"` // Minimum number of seconds for which a newly created pod should be ready
// without any of its container crashing, for it to be considered available.
// Defaults to 0 (pod will be considered available as soon as it is ready)
// +optional
MinReadySeconds int32 `json:"minReadySeconds,omitempty" protobuf:"varint,5,opt,name=minReadySeconds"` // The number of old ReplicaSets to retain to allow rollback.
// This is a pointer to distinguish between explicit zero and not specified.
// Defaults to 10.
// +optional
RevisionHistoryLimit *int32 `json:"revisionHistoryLimit,omitempty" protobuf:"varint,6,opt,name=revisionHistoryLimit"` // Indicates that the deployment is paused.
// +optional
Paused bool `json:"paused,omitempty" protobuf:"varint,7,opt,name=paused"` // The maximum time in seconds for a deployment to make progress before it
// is considered to be failed. The deployment controller will continue to
// process failed deployments and a condition with a ProgressDeadlineExceeded
// reason will be surfaced in the deployment status. Note that progress will
// not be estimated during the time a deployment is paused. Defaults to 600s.
ProgressDeadlineSeconds *int32 `json:"progressDeadlineSeconds,omitempty" protobuf:"varint,9,opt,name=progressDeadlineSeconds"`
}

此处简单创建一个deployment控制器,故只需副本数量 选择器 template即可。

在资源清单中的spec属性的为如下结构体

type PodTemplateSpec struct {
// Standard object's metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the pod.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
// +optional
Spec PodSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
}

故此处需要定义,副本数量,选择器,podspec,而副本数量为一个int32类型的数字,标签选择器为一个map[string]string的数组

故定义如下

repl := int32(1) // 副本数量

match := make(map[string]string)  // 标签选择器
match["app"] = "nginx"
var podSpec = apiv1.Container {
Name: "golang-client",
Image:"redis",
ImagePullPolicy:"IfNotPresent",
}
containers := []apiv1.Container{podSpec} var templateSpec = apiv1.PodTemplateSpec{
ObjectMeta:metav1.ObjectMeta{
Name:"testpod",
Labels:match,
},
Spec: apiv1.PodSpec{
Containers:containers,
},
}

定义deployment控制器格式

selecter :=  metav1.LabelSelector{
MatchLabels: match,
}
deploy := appv1.Deployment{
ObjectMeta:metav1.ObjectMeta{
Name: "testgolangclient",
}, Spec: appv1.DeploymentSpec{
Replicas: &repl,
Selector:&selecter,
Template:templateSpec,
}, }

创建的deplyment 控制器

podsClient,err := clientset.AppsV1().Deployments("default" /* 名称空间 */).Create(&deploy)
 

kubernetes客户端client-go使用的更多相关文章

  1. Axis 生成客户端client stub文件

    [转自] http://blog.csdn.net/qiao000_000/article/details/5568442 开发前,有个同事先给我们不熟悉Web Service的程序员进行了一些培训, ...

  2. Kubernetes客户端和管理界面大集合

    今天给大家介绍目前市面上常用的kubernetes管理工具,总有一款适合您~~~ 简介 Kubectl K9s Kubernetes-Dashboard Rancher Kuboard Lens Oc ...

  3. kubernetes 客户端KubeClient使用及常用api

    KubeClient是kubernetes 的C#语言客户端简单易用,KubeClient是.NET Core(目标netstandard1.4)的可扩展Kubernetes API客户端, gith ...

  4. 最好的Kubernetes客户端Java库fabric8io,快来自定义你的操作

    我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 Kubernetes Java客户端 对于Kubernetes集群的操作,官方提供了命令行工具kubectl,这也是我 ...

  5. cas单点登录系统:客户端(client)详细配置

    最近一直在研究cas登录中心这一块的应用,分享一下记录的一些笔记和心得.后面会把cas-server端的配置和重构,另外还有这几天再搞nginx+cas的https反向代理配置,以及cas的证书相关的 ...

  6. java 和 C++ Socket通信(java作为服务端server,C++作为客户端client,解决中文乱码问题GBK和UTF8)

    原文链接: http://www.cnblogs.com/kenkofox/archive/2010/04/25/1719649.html 代码: http://files.cnblogs.com/k ...

  7. cas单点登录系统:客户端(client)详细配置(包含统一单点注销配置)

    最近一直在研究cas登录中心这一块的应用,分享一下记录的一些笔记和心得.后面会把cas-server端的配置和重构,另外还有这几天再搞nginx+cas的https反向代理配置,以及cas的证书相关的 ...

  8. Kubernetes 的 Client Libraries 的使用

    说明 kubernetes 估计会成为 linux 一样的存在,client-go 是它的 go sdk,client-go/examples/ 给出了一些用例,但是数量比较少. api Resour ...

  9. Kubernetes Python Client 初体验之node操作

    今天讲一下k8s中对于各个实物节点node的操作. 首先是获取所有nodes信息: self.config.kube_config.load_kube_config(config_file=" ...

  10. Kubernetes Python Client 初体验之Deployment

    Kubernetes官方推荐我们使用各种Controller来管理Pod的生命周期,今天写一个最常用的Deployment的操作例子. 首先是创建Deployment: with open(path. ...

随机推荐

  1. 关于生产环境改用G1垃圾收集器的思考

    背景 由于我们的业务量非常大,响应延迟要求高.目前沿用的老的ParNew+CMS已经不能支撑业务的需求.平均一台机器在1个月内有1次秒级别的stop the world.对系统来说是个巨大的隐患.所以 ...

  2. 20182217_刘洪宇 后门原理与实践 EXP2

    1.后门概念 后门就是不经过正常认证流程而访问系统的通道. 哪里有后门呢? 编译器留后门 操作系统留后门 最常见的当然还是应用程序中留后门 还有就是潜伏于操作系统中或伪装为特定应用的专用后门程序. - ...

  3. pwn题命令行解题脚本

    目录 脚本说明 脚本内容 使用 使用示例 参考与引用 脚本说明 这是专门为本地调试与远程答题准备的脚本,依靠命令行参数进行控制. 本脚本支持的功能有: 本地调试 开启tmux调试 设置gdb断点,支持 ...

  4. UnboundLocalError: local variable 'foo' referenced before assignment Python常见错误

    在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在) 在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的, 使用规则:如果在函数中定义了任何东西,如果它只是在函数中使用 ...

  5. crx 文件安装 如何安装 Chrome插件

          Chrome 67 版本(大概2018.06.06的更新包)开始,插件已经无法离线安装啦,也就是自己无法使用crx文件安装插件,   而只能从chrome.google.com/webst ...

  6. Python基础(十六):文件读写,靠这一篇就够了!

    文件读写的流程 类比windows中手动操作txt文档,说明python中如何操作txt文件? 什么是文件的内存对象(文件句柄)? 演示怎么读取文件 ① 演示如下 f = open(r"D: ...

  7. 【设计模式】- 生成器模式(Builder)

    生成器模式 建造者模式.Builder 生成器模式 也叫建造者模式,可以理解成可以分步骤创建一个复杂的对象.在该模式中允许你使用相同的创建代码生成不同类型和形式的对象. 生成器的结构模式 生成器(Bu ...

  8. Dynamics CRM安装教程九(续):自建证书的CRM项目客户端设置CRM访问

    配置完IFD之后就可以为客户端电脑配置访问CRM了首先到CA证书服务器中把证书下载下来,打开CA服务器的浏览器,输入地址http://stg-ad/certsrv/ 其中stg-ad是机器名之后点击下 ...

  9. MyBatis-Plus笔记(入门)

    作者:故事我忘了¢个人微信公众号:程序猿的月光宝盒 官方文档 https://mybatis.plus/guide/ 本篇基于springboot,mybatis Plus的版本为3.4.2 本篇对应 ...

  10. Leedcode算法专题训练(分治法)

    归并排序就是一个用分治法的经典例子,这里我用它来举例描述一下上面的步骤: 1.归并排序首先把原问题拆分成2个规模更小的子问题. 2.递归地求解子问题,当子问题规模足够小时,可以一下子解决它.在这个例子 ...