HAOJX

dynamic-Client的使用方法

字数统计: 188阅读时长: 1 min
2021/10/09 Share

第一步先创建一个dynamic client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package kubeConfig

import (
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"log"
)

func InitConfig() *rest.Config {
config, err := clientcmd.BuildConfigFromFlags("", "config")
if err != nil {
log.Fatal(err)
}
return config
}

func InitClient() *kubernetes.Clientset {
client, err := kubernetes.NewForConfig(InitConfig())
if err != nil {
log.Fatal(err)
}
return client
}

func InitDynamicClient() dynamic.Interface {
config, err := dynamic.NewForConfig(InitConfig())
if err != nil {
log.Fatal(err)
}
return config
}

之后使用这个动态客户端

简单的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"kube-base3/lib/kubeConfig"
"log"
)

func main() {
dClient := kubeConfig.InitDynamicClient()
gvr := schema.GroupVersionResource{
Group: "apps",
Version: "v1",
Resource: "deployments",
}
list, err := dClient.Resource(gvr).Namespace("default").List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Fatal(err)
}
for _, item := range list.Items {
fmt.Println(item.GetName())
}
}
CATALOG