HAOJX

写个通用代码来模拟kubectl apply文件(kustomize模式)

字数统计: 288阅读时长: 1 min
2022/01/03 Share

这个yaml可以有三个横岗的那种 实现多个文件合并来apply

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main

import (
"bytes"
"context"
"fmt"
"io"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
syaml "k8s.io/apimachinery/pkg/runtime/serializer/yaml"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/restmapper"
"kube-base3/lib/kubeConfig"
"log"
"os/exec"
)

func kust(path string) []byte {
cmd := exec.Command("kustomize", "build", path)
var ret bytes.Buffer
cmd.Stdout = &ret
if err := cmd.Run(); err != nil {
fmt.Println(err)
return nil
}
return ret.Bytes()
}
func main() {
dc := kubeConfig.InitDynamicClient()
client := kubeConfig.InitClient()
b := kust("pkg/deploy")
decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(b), len(b))

for {
var rawObj runtime.RawExtension
err := decoder.Decode(&rawObj)

if err != nil {
if err == io.EOF {
break
} else {
log.Fatal(err)
}

}

obj, gvk, err := syaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme).
Decode(rawObj.Raw, nil, nil)
if err != nil {
log.Fatal(err)
}

unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
log.Fatal(err)
}

unstructuredObj := &unstructured.Unstructured{Object: unstructuredMap}

gr, err := restmapper.GetAPIGroupResources(client.Discovery())
if err != nil {
log.Fatal(err)
}

mapper := restmapper.NewDiscoveryRESTMapper(gr)
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
log.Fatal(err)
}

gvr := schema.GroupVersionResource{
Group: mapping.Resource.Group,
Version: mapping.Resource.Version,
Resource: mapping.Resource.Resource,
}

_, err = dc.Resource(gvr).Namespace(unstructuredObj.GetNamespace()).
Create(context.Background(), unstructuredObj, metav1.CreateOptions{})

if err != nil {
log.Fatal(err)
}

}
}
CATALOG