使用client-go工具调用kubernetes API接口的教程详解(v1.17版本)

 更新时间:2021年08月25日 10:09:48   作者:运维董伟振  
这篇文章主要介绍了使用client-go工具调kubernetes API接口(v1.17版本),本文通过图文实例相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

说明

可以调取k8s API 接口的工具有很多,这里我就介绍下client-go

gitlab上client-go项目地址: https://github.com/kubernetes/client-go  

这个工具是由kubernetes官方指定维护的,大家可以放心使用

在这里插入图片描述

效果

运行完成后,可以直接获取k8s集群信息等

在这里插入图片描述

实现

1、拉取工具源码

注意事项:https://github.com/kubernetes/client-go/blob/master/INSTALL.md

总结:一定要拉取跟集群对应版本的工具源码,比如我这里集群是1.17版本,那我就拉取17版本

go get k8s.io/client-go@v0.17.0

我是1.17版本的集群,所有依赖文件放在这了,可以直接使用client-go k8s1.17 api

2、创建目录结构

在这里插入图片描述

集群的角色配置文件(默认在/root/.kube/config)
kube/config

查询代码实例

查询pod信息

查看ferry命名空间下pod的信息,pod名字、pod的IP

vim kube-api.go

package main

import (
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"k8s.io/client-go/kubernetes"

	"k8s.io/client-go/tools/clientcmd"
)

func main() {

	config, err := clientcmd.BuildConfigFromFlags("", "kube/config")
	if err != nil {
		panic(err)
	}
	client, _ := kubernetes.NewForConfig(config)
	pods ,err := client.CoreV1().Pods("ferry").List(metav1.ListOptions{})
	if err != nil {
		fmt.Println(err)
		return
	}

	for _,v := range  pods.Items {
		fmt.Printf(" 命名空间是:%v\n pod名字:%v\n IP:%v\n\n",v.Namespace,v.Name,v.Status.PodIP)
	}
}

自动关联依赖

go mod tidy

运行结果

$ go run kube-api.go

 命名空间是:ferry
 pod名字:ferry-backend-7949596679-h8lxb
 IP:10.42.1.14

 命名空间是:ferry
 pod名字:ferry-mysql-8db8d49f7-6psbv
 IP:10.42.1.11

查询一个pod是否在一个命名空间下

https://github.com/kubernetes/client-go/blob/master/examples/in-cluster-client-configuration/main.go
每3秒检查下nginx-74959fc858-cp48w是否在default命名空间下

package main

import (
	"context"
	"fmt"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"time"
)

func main() {

	config, err := clientcmd.BuildConfigFromFlags("", "kube/config")
	if err != nil {
		panic(err)
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
	for {
		// get pods in all the namespaces by omitting namespace
		// Or specify namespace to get pods in particular namespace
		pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
		if err != nil {
			panic(err.Error())
		}
		fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))

		// Examples for error handling:
		// - Use helper functions e.g. errors.IsNotFound()
		// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
		_, err = clientset.CoreV1().Pods("default").Get(context.TODO(), "nginx-74959fc858-cp48w", metav1.GetOptions{})
		if errors.IsNotFound(err) {
			fmt.Printf("Pod nginx-74959fc858-cp48w not found in default namespace\n")
		} else if statusError, isStatus := err.(*errors.StatusError); isStatus {
			fmt.Printf("Error getting pod %v\n", statusError.ErrStatus.Message)
		} else if err != nil {
			panic(err.Error())
		} else {
			fmt.Printf("Found nginx-74959fc858-cp48w pod in default namespace\n")
		}

	 time.Sleep(3 * time.Second)
	}
}

运行结果

$ go run kube-api.go
There are 22 pods in the cluster
Found nginx-74959fc858-cp48w pod in default namespace
There are 22 pods in the cluster
Found nginx-74959fc858-cp48w pod in default namespace
There are 22 pods in the cluster
Found nginx-74959fc858-cp48w pod in default namespace
There are 23 pods in the cluster
Found nginx-74959fc858-cp48w pod in default namespace
There are 22 pods in the cluster
Found nginx-74959fc858-cp48w pod in default namespace
There are 22 pods in the cluster
Found nginx-74959fc858-cp48w pod in default namespace
There are 21 pods in the cluster
\\在集群种手动删除了这个pod
Pod nginx-74959fc858-cp48w not found in default namespace
There are 21 pods in the cluster
Pod nginx-74959fc858-cp48w not found in default namespace

查询deployment服务类型信息

查询default命名空间下的deployment服务信息,服务名字、服务副本数

package main

import (
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"k8s.io/client-go/kubernetes"

	"k8s.io/client-go/tools/clientcmd"
)

func main() {

	config, err := clientcmd.BuildConfigFromFlags("", "kube/config")
	if err != nil {
		panic(err)
	}
	client, _ := kubernetes.NewForConfig(config)
	deploymentList, err := client.AppsV1().Deployments("default").List(metav1.ListOptions{})
	if err != nil {
		fmt.Println(err)
		return
	}

	for _,v := range deploymentList.Items {
		fmt.Printf(" 命名空间是:%v\n deployment服务名字:%v\n 副本个数:%v\n\n",v.Namespace,v.Name,v.Status.Replicas)
	}

}

运行结果

$ go run kube-api.go
 命名空间是:default
 deployment服务名字:nginx
 副本个数:2

创建deployment资源

https://github.com/kubernetes/client-go/blob/master/examples/create-update-delete-deployment/main.go

复制一个config文件到当前目录下

在这里插入图片描述

创建一个deployment类型的nginx服务

vim deployment-create.go

package main

import (
	"context"
	"flag"
	"fmt"

	"path/filepath"

	appsv1 "k8s.io/api/apps/v1"
	apiv1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	//
	// Uncomment to load all auth plugins
	// _ "k8s.io/client-go/plugin/pkg/client/auth"
	//
	// Or uncomment to load specific auth plugins
	// _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)

func main() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join("config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err)
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err)
	}

	deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)

	deployment := &appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name: "nginx-deployment",
		},
		Spec: appsv1.DeploymentSpec{
			Replicas: int32Ptr(2),
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"app": "nginx",
				},
			},
			Template: apiv1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"app": "nginx",
					},
				},
				Spec: apiv1.PodSpec{
					Containers: []apiv1.Container{
						{
							Name:  "web",
							Image: "nginx:1.12",
							Ports: []apiv1.ContainerPort{
								{
									Name:          "http",
									Protocol:      apiv1.ProtocolTCP,
									ContainerPort: 80,
								},
							},
						},
					},
				},
			},
		},
	}

	// Create Deployment
	fmt.Println("Creating deployment nginx...")
	result, err := deploymentsClient.Create(context.TODO(), deployment, metav1.CreateOptions{})
	if err != nil {
		panic(err)
	}
	fmt.Printf("Created deployment %q.\n", result.GetObjectMeta().GetName())

}

运行结果

$ go run deployment-create.go
Creating deployment nginx...
Created deployment "nginx-deployment".

更新deployment类型服务

https://github.com/kubernetes/client-go/blob/master/examples/create-update-delete-deployment/main.go
更改服务的副本数,由上一步创建的2修改成1,并修改镜像由nginx1.12–>nginx1.13

package main

import (
	"context"
	"flag"
	"fmt"
	"path/filepath"

	apiv1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"k8s.io/client-go/util/retry"
	//
	// Uncomment to load all auth plugins
	// _ "k8s.io/client-go/plugin/pkg/client/auth"
	//
	// Or uncomment to load specific auth plugins
	// _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)

func main() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join("config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err)
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err)
	}

	deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)

	retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
		// Retrieve the latest version of Deployment before attempting update
		// RetryOnConflict uses exponential backoff to avoid exhausting the apiserver
		result, getErr := deploymentsClient.Get(context.TODO(), "nginx-deployment", metav1.GetOptions{})
		if getErr != nil {
			panic(fmt.Errorf("Failed to get latest version of Deployment: %v", getErr))
		}

		result.Spec.Replicas = int32Ptr(1)                           // reduce replica count
		result.Spec.Template.Spec.Containers[0].Image = "nginx:1.13" // change nginx version
		_, updateErr := deploymentsClient.Update(context.TODO(), result, metav1.UpdateOptions{})
		return updateErr
	})
	if retryErr != nil {
		panic(fmt.Errorf("Update failed: %v", retryErr))
	}
	fmt.Println("Updated deployment nginx")

}
func int32Ptr(i int32) *int32 { return &i }

运行结果

$ go run deployment-update.go
Updated deployment nginx

在这里插入图片描述

删除deployment类型服务

删除上面创建的nginx-deployment资源,删除之前添加了确认语句

package main

import (
	"bufio"
	"context"
	"flag"
	"fmt"
	"os"
	"path/filepath"

	apiv1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	//
	// Uncomment to load all auth plugins
	// _ "k8s.io/client-go/plugin/pkg/client/auth"
	//
	// Or uncomment to load specific auth plugins
	// _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
	// _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
)

func main() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join( "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err)
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err)
	}

	deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)

     prompt()
	fmt.Println("Deleting deployment nginx...")
	deletePolicy := metav1.DeletePropagationForeground
	if err := deploymentsClient.Delete(context.TODO(), "nginx-deployment", metav1.DeleteOptions{
		PropagationPolicy: &deletePolicy,
	}); err != nil {
		panic(err)
	}
	fmt.Println("Deleted deployment.")
}

func prompt() {
	fmt.Printf("-> Press Return key to continue, will delete!")
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		break
	}
	if err := scanner.Err(); err != nil {
		panic(err)
	}
	fmt.Println()
}

func int32Ptr(i int32) *int32 { return &i }

运行结果

$ go run deployment-delete.go
-> Press Return key to continue, will delete! 这里点击回车后继续删除资源

Deleting deployment nginx...
Deleted deployment.

在这里插入图片描述

到此这篇关于使用client-go工具调kubernetes API接口(v1.17版本)的文章就介绍到这了,更多相关client-go调用kubernetes API内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 简单聊聊为什么说Go语言字符串是不可变的

    简单聊聊为什么说Go语言字符串是不可变的

    最近有读者留言说,平时在写代码的过程中,是会对字符串进行修改的,但网上都说 Go 语言字符串是不可变的,这是为什么呢,本文就来和大家简单讲讲
    2023-05-05
  • golang如何替换换行符

    golang如何替换换行符

    这篇文章主要介绍了golang如何替换换行符问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-07-07
  • Golang中的包及包管理工具go mod详解

    Golang中的包及包管理工具go mod详解

    这篇文章主要介绍了Golang中的包及包管理工具go mod,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-07-07
  • Golang使用pprof检查内存泄漏的全过程

    Golang使用pprof检查内存泄漏的全过程

    pprof 是golang提供的一款分析工具,可以分析CPU,内存的使用情况,本篇文章关注它在分析内存泄漏方面的应用,本文给大家介绍了Golang使用pprof检查内存泄漏的全过程,文中通过代码给大家介绍的非常详细,需要的朋友可以参考下
    2024-02-02
  • 一文带你使用Golang实现SSH客户端

    一文带你使用Golang实现SSH客户端

    SSH 全称为 Secure Shell,是一种用于安全地远程登录到网络上的其他计算机的网络协议,本文主要为大家详细介绍了如何使用 Golang 实现 SSH 客户端,需要的可以参考下
    2023-11-11
  • Golang实现Md5校验的代码示例

    Golang实现Md5校验的代码示例

    最近项目中有个需求,就是地图文件下发后,接收方需要文件的md5值,和接收到的文件做比对,以免文件不完整,引起bug,于是测试了下本地文件和远程文件的md5计算,所以本文给大家介绍了Golang实现Md5校验,需要的朋友可以参考下
    2024-07-07
  • Go实现分布式唯一ID的生成之雪花算法

    Go实现分布式唯一ID的生成之雪花算法

    本文主要介绍了Go实现分布式唯一ID的生成之雪花算法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-05-05
  • go语言限制协程并发数的方案详情

    go语言限制协程并发数的方案详情

    一个线程中可以有任意多个协程,但某一时刻只能有一个协程在运行,多个协程分享该线程分配到的计算机资源,接下来通过本文给大家介绍go语言限制协程的并发数的方案详情,感兴趣的朋友一起看看吧
    2022-01-01
  • Go语言reflect包的反射机制基本用法示例

    Go语言reflect包的反射机制基本用法示例

    反射在处理接口和类型断言、开发通用功能或者设计框架时尤为重要,本文将深入探索 Go 语言中的反射机制,通过具体的示例展示如何使用 reflect 包,让你能够在 Go 项目中有效地利用这一强大的工具
    2023-11-11
  • go语言题解LeetCode506相对名次示例详解

    go语言题解LeetCode506相对名次示例详解

    这篇文章主要为大家介绍了go语言题解LeetCode506相对名次示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12

最新评论