kubernetes客戶端client-go使用


下載地址: 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)

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM