下载地址: 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. Spring笔记(三)

    Spring AOP 一.AOP(概念) 1. 什么是AOP 面向切面编程(方面),利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各个部分之间的耦合度降低,提高程序的可重用性,同时提高了 ...

  2. Java单链表反转图文详解

    Java单链表反转图文详解 最近在回顾链表反转问题中,突然有一些新的发现和收获,特此整理一下,与大家分享 背景回顾 单链表的存储结构如图: 数据域存放数据元素,指针域存放后继结点地址 我们以一条 N1 ...

  3. LiteOS内核源码分析:任务LOS_Schedule

    摘要:调度,Schedule也称为Dispatch,是操作系统的一个重要模块,它负责选择系统要处理的下一个任务.调度模块需要协调处于就绪状态的任务对资源的竞争,按优先级策略从就绪队列中获取高优先级的任 ...

  4. K8S 上部署 Redis-cluster 三主三从 集群

    介绍 Redis代表REmote DIctionary Server是一种开源的内存中数据存储,通常用作数据库,缓存或消息代理.它可以存储和操作高级数据类型,例如列表,地图,集合和排序集合. 由于Re ...

  5. [BFS]骑士旅行

    骑士旅行 Description 在一个n m 格子的棋盘上,有一只国际象棋的骑士在棋盘的左下角 (1;1)(如图1),骑士只能根据象棋的规则进行移动,要么横向跳动一格纵向跳动两格,要么纵向跳动一格横 ...

  6. Scrapy框架的安装

    Win+R 输入cmd打开命令行 我们先把pip升级到最新版,输入代码如下: pip install --upgrade pip 不过一般这种更新方式会经常性出错,安装文件在下载到一半时就会超时报错 ...

  7. HTML(〇):简介导读

    网页 什么是网页 网站(Website):是指在因特网上根据一定的规则,使用HTML(标准通用标记语言)等工具制作的用于展示特定内容相关网页的集合. 网页(webpage):是网站中的一页,通常是HT ...

  8. 结对编程_stage1

    项目 内容 这个作业属于哪个课程 2021春季软件工程(罗杰 任健) 这个作业的要求在哪里 结对项目-第一阶段 我在这个课程的目标是 从实践中学习软件工程相关知识(结构化分析和设计方法.敏捷开发方法. ...

  9. Java中注释的形式

    单行注释 单行注释 // #双斜杠 快捷键:Ctrl + / 多行注释 多行注释 /* */ #单斜杠星号 星号单斜杠 快捷键:Ctrl + shift + / 文档注释 多行注释 /** */ #单 ...

  10. leetcode 刷题(数组篇)15题 三数之和 (双指针)

    很有意思的一道题,值得好好思考,虽然难度只有Mid,但是个人觉得不比Hard简单 题目描述 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b ...