HAOJX

生成config和client的几种写法

字数统计: 279阅读时长: 1 min
2021/09/29 Share

第一种

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"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
"log"
)

func main() {
configFlags:=genericclioptions.NewConfigFlags(true)
config,err:=configFlags.ToRawKubeConfigLoader().ClientConfig()
if err!=nil{log.Fatalln(err)}

client,err:=kubernetes.NewForConfig(config)
if err!=nil{log.Fatalln(err)}

list,err:=client.CoreV1().Pods("default").List(context.Background(),v1.ListOptions{})
if err!=nil{log.Fatalln(err)}
for _,pod:=range list.Items{
fmt.Println(pod.Name)
}

}

第二种

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package k8sconfig

import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"log"
"os"
)
//全局变量
type K8sConfig struct {}

func NewK8sConfig() *K8sConfig {
return &K8sConfig{}
}
const NSFile="/var/run/secrets/kubernetes.io/serviceaccount/namespace"

//POD里 体内
func K8sRestConfigInPod() *rest.Config{
config,err:=rest.InClusterConfig()
if err!=nil{
log.Fatal(err)
}
return config
}
// 获取 config对象
func (*K8sConfig) K8sRestConfig() *rest.Config{
if os.Getenv("release")=="1"{ //自定义环境
log.Println("run in cluster")
return K8sRestConfigInPod()
}
log.Println("run outside cluster")
config, err := clientcmd.BuildConfigFromFlags("","./resources/config" )
if err!=nil{
log.Fatal(err)
}
//config.Insecure=true
return config
}

func (this *K8sConfig)InitClient() *kubernetes.Clientset{
//config:=&rest.Config{
// Host:"<http://192.168.92.129:8001>",
// //Host: "<http://127.0.0.1:8001>",
//}
//config,err:= clientcmd.BuildConfigFromFlags("","config")
//if err != nil {
// log.Fatal(err)
//}
c,err:=kubernetes.NewForConfig(this.K8sRestConfig())
if err!=nil{
log.Fatal(err)
}
return c
}
CATALOG