-
Notifications
You must be signed in to change notification settings - Fork 249
/
k8sdeployment.go
123 lines (117 loc) · 2.59 KB
/
k8sdeployment.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package codegen
import (
"github.com/Jeffail/gabs/v2"
"github.com/goccy/go-yaml"
"github.com/sirupsen/logrus"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
)
var deploymentTmpl = `apiVersion: apps/v1
kind: Deployment
metadata:
name: {{.SvcName}}-deployment
spec:
replicas: 1
selector:
matchLabels:
app: {{.SvcName}}
template:
metadata:
labels:
app: {{.SvcName}}
spec:
containers:
- name: {{.SvcName}}
image: {{.Image}}
imagePullPolicy: Always
ports:
- name: http-port
containerPort: 6060
protocol: TCP
resources:
requests:
cpu: 100m
memory: 128Mi
restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
name: {{.SvcName}}-service
spec:
type: LoadBalancer
externalTrafficPolicy: Cluster
selector:
app: {{.SvcName}}
ports:
- protocol: TCP
port: 6060
targetPort: 6060`
// GenK8sDeployment generates deployment kind yaml file for kubernetes deploy.
func GenK8sDeployment(dir string, svcname, image string) {
var (
f *os.File
tpl *template.Template
)
file := filepath.Join(dir, svcname+"_deployment.yaml")
if _, err := os.Stat(file); os.IsNotExist(err) {
if f, err = os.Create(file); err != nil {
panic(err)
}
defer f.Close()
if tpl, err = template.New("deployment.tmpl").Parse(deploymentTmpl); err != nil {
panic(err)
}
if err = tpl.Execute(f, struct {
SvcName string
Image string
}{
SvcName: svcname,
Image: image,
}); err != nil {
panic(err)
}
} else {
logrus.Warnf("image version will be modified in file %s", file)
err = ioutil.WriteFile(file, modifyVersion(file, image), os.ModePerm)
if err != nil {
panic(err)
}
}
}
func modifyVersion(yfile string, image string) []byte {
var (
f *os.File
err error
raw, jdeployment, ddeployment []byte
deployment string
)
if f, err = os.Open(yfile); err != nil {
panic(err)
}
defer f.Close()
raw, err = ioutil.ReadAll(f)
if err != nil {
panic(err)
}
blocks := strings.Split(string(raw), "---")
deployment = blocks[0]
jdeployment, err = yaml.YAMLToJSON([]byte(deployment))
if err != nil {
panic(err)
}
c, err := gabs.ParseJSON(jdeployment)
if err != nil {
panic(err)
}
c.Set(image, gabs.DotPathToSlice("spec.template.spec.containers.0.image")...)
if err != nil {
panic(err)
}
ddeployment, _ = yaml.JSONToYAML(c.Bytes())
blocks[0] = string(ddeployment)
return []byte(strings.Join(blocks, "---"))
}