最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用client-go工具調(diào)用kubernetes API接口的教程詳解(v1.17版本)

 更新時間:2021年08月25日 10:09:48   作者:運維董偉振  
這篇文章主要介紹了使用client-go工具調(diào)kubernetes API接口(v1.17版本),本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

說明

可以調(diào)取k8s API 接口的工具有很多,這里我就介紹下client-go

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

這個工具是由kubernetes官方指定維護的,大家可以放心使用

在這里插入圖片描述

效果

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

在這里插入圖片描述

實現(xiàn)

1、拉取工具源碼

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

總結(jié):一定要拉取跟集群對應(yīng)版本的工具源碼,比如我這里集群是1.17版本,那我就拉取17版本

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

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

2、創(chuàng)建目錄結(jié)構(gòu)

在這里插入圖片描述

集群的角色配置文件(默認在/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)
	}
}

自動關(guān)聯(lián)依賴

go mod tidy

運行結(jié)果

$ 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)
	}
}

運行結(jié)果

$ 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服務(wù)類型信息

查詢default命名空間下的deployment服務(wù)信息,服務(wù)名字、服務(wù)副本數(shù)

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服務(wù)名字:%v\n 副本個數(shù):%v\n\n",v.Namespace,v.Name,v.Status.Replicas)
	}

}

運行結(jié)果

$ go run kube-api.go
 命名空間是:default
 deployment服務(wù)名字:nginx
 副本個數(shù):2

創(chuàng)建deployment資源

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

復(fù)制一個config文件到當前目錄下

在這里插入圖片描述

創(chuàng)建一個deployment類型的nginx服務(wù)

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())

}

運行結(jié)果

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

更新deployment類型服務(wù)

https://github.com/kubernetes/client-go/blob/master/examples/create-update-delete-deployment/main.go
更改服務(wù)的副本數(shù),由上一步創(chuàng)建的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 }

運行結(jié)果

$ go run deployment-update.go
Updated deployment nginx

在這里插入圖片描述

刪除deployment類型服務(wù)

刪除上面創(chuàng)建的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 }

運行結(jié)果

$ go run deployment-delete.go
-> Press Return key to continue, will delete! 這里點擊回車后繼續(xù)刪除資源

Deleting deployment nginx...
Deleted deployment.

在這里插入圖片描述

到此這篇關(guān)于使用client-go工具調(diào)kubernetes API接口(v1.17版本)的文章就介紹到這了,更多相關(guān)client-go調(diào)用kubernetes API內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Go官方限流器的用法詳解

    Go官方限流器的用法詳解

    限流器是提升服務(wù)穩(wěn)定性的非常重要的組件,本文主要介紹了Go官方限流器的用法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • Golang調(diào)用FFmpeg轉(zhuǎn)換視頻流的實現(xiàn)

    Golang調(diào)用FFmpeg轉(zhuǎn)換視頻流的實現(xiàn)

    本文主要介紹了Golang調(diào)用FFmpeg轉(zhuǎn)換視頻流,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • Golang使用JWT進行認證和加密的示例詳解

    Golang使用JWT進行認證和加密的示例詳解

    JWT是一個簽名的JSON對象,通常用作Oauth2的Bearer?token,JWT包括三個用.分割的部分。本文將利用JWT進行認證和加密,感興趣的可以了解一下
    2023-02-02
  • GO語言延遲函數(shù)defer用法詳解

    GO語言延遲函數(shù)defer用法詳解

    本文主要介紹了GO語言延遲函數(shù)defer用法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-03-03
  • 淺析Go語言中Channel的各種用法

    淺析Go語言中Channel的各種用法

    這篇文章主要帶大家一起來學習一下Go語言中的if語句,也就是大家口中的判斷語句。文中的示例代碼講解詳細,對我們學習Go語言有一定幫助,需要的可以參考一下
    2022-11-11
  • golang sync.Pool 指針數(shù)據(jù)覆蓋問題解決

    golang sync.Pool 指針數(shù)據(jù)覆蓋問題解決

    本文主要介紹了使用sync.Pool時遇到指針數(shù)據(jù)覆蓋的問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2025-03-03
  • Golang filepath包常用函數(shù)詳解

    Golang filepath包常用函數(shù)詳解

    本文介紹與文件路徑相關(guān)包,該工具包位于path/filepath中,該包試圖與目標操作系統(tǒng)定義的文件路徑兼容。本文介紹一些常用函數(shù),如獲取文件絕對路徑,獲取文件名或目錄名、遍歷文件、分割文件路徑、文件名模式匹配等函數(shù),并給具體示例進行說明
    2023-02-02
  • 一文帶你了解Go中跟蹤函數(shù)調(diào)用鏈的實現(xiàn)

    一文帶你了解Go中跟蹤函數(shù)調(diào)用鏈的實現(xiàn)

    這篇文章主要為大家詳細介紹了go如何實現(xiàn)一個自動注入跟蹤代碼,并輸出有層次感的函數(shù)調(diào)用鏈跟蹤命令行工具,感興趣的小伙伴可以跟隨小編一起學習一下
    2023-11-11
  • 利用go-kit組件進行服務(wù)注冊與發(fā)現(xiàn)和健康檢查的操作

    利用go-kit組件進行服務(wù)注冊與發(fā)現(xiàn)和健康檢查的操作

    這篇文章主要介紹了利用go-kit組件進行服務(wù)注冊與發(fā)現(xiàn)和健康檢查的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • Go語言中的自定義錯誤類型

    Go語言中的自定義錯誤類型

    本文主要介紹了Go語言中的自定義錯誤類型,通過定義結(jié)構(gòu)體并實現(xiàn)Error接口,創(chuàng)建包含參數(shù)和錯誤信息的自定義錯誤,具有一定的參考價值,感興趣的可以了解一下
    2025-05-05

最新評論

高邮市| 呼图壁县| 亳州市| 凤山市| 旅游| 应用必备| 塘沽区| 华阴市| 和田市| 平乡县| 普兰店市| 金秀| 中卫市| 金乡县| 汝州市| 二手房| 济阳县| 迭部县| 新田县| 固镇县| 白山市| 永善县| 璧山县| 乌兰察布市| 神农架林区| 台湾省| 滁州市| 体育| 金华市| 祁东县| 嘉义县| 高碑店市| 珠海市| 宁夏| 五寨县| 福建省| 宜章县| 大关县| 邛崃市| 秭归县| 麦盖提县|