-
Notifications
You must be signed in to change notification settings - Fork 9
/
terraform.go
284 lines (234 loc) · 7.09 KB
/
terraform.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package scaffold
import (
"bytes"
"fmt"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"golang.org/x/exp/maps"
"golang.org/x/mod/semver"
"github.com/pluralsh/plural-cli/pkg/api"
"github.com/pluralsh/plural-cli/pkg/config"
"github.com/pluralsh/plural-cli/pkg/template"
"github.com/pluralsh/plural-cli/pkg/utils"
"github.com/pluralsh/plural-cli/pkg/utils/pathing"
"github.com/pluralsh/plural-cli/pkg/wkspace"
)
const moduleTemplate = `module "{{ .Values.name }}" {
source = "{{ .Values.path }}"
### BEGIN MANUAL SECTION <<{{ .Values.name }}>>
{{ .Values.Manual }}
### END MANUAL SECTION <<{{ .Values.name }}>>
{{ .Values.conf | nindent 2 }}
{{ range $key, $val := .Values.deps }}
{{ $key }} = module.{{ $val }}
{{- end }}
}
`
const outputTemplate = `output "{{ .Name }}" {
value = module.{{ .Module }}.{{ .Value }}
sensitive = true
}
`
const helpDoc = `
############## Helpful Hints ###################
# Any configuration updates should be done in this file in a manual section. You can also create files alongside this one,
# and plural build will preserve them. That's the ideal strategy if you want to add additional resources like a sql instance
# or vpn gateway.
# The submodule folders within this directory are generated by plural build and we cannot guarantee a change in
# them will be merged properly.
#################################################
`
func (scaffold *Scaffold) handleTerraform(wk *wkspace.Workspace) error {
repo := wk.Installation.Repository
providerCtx := buildContext(wk, repo.Name, wk.Terraform)
var providerVersions semver.ByVersion
if len(wk.Terraform) == 0 {
return nil
}
for i := range wk.Terraform {
providerVersions = append(providerVersions, wk.Terraform[i].Terraform.Dependencies.ProviderVsn)
}
semver.Sort(providerVersions)
// use the latest version of the TF template for the provider
backend, err := wk.Provider.CreateBackend(repo.Name, providerVersions[providerVersions.Len()-1], providerCtx)
if err != nil {
return err
}
apps, err := NewApplications()
if err != nil {
return err
}
if err := scaffold.untarModules(wk); err != nil {
return err
}
mainFile := pathing.SanitizeFilepath(filepath.Join(scaffold.Root, "main.tf"))
contents, err := utils.ReadFile(mainFile)
if err != nil {
contents = ""
}
var modules = make([]string, len(wk.Terraform)+1)
modules[0] = helpDoc + backend
ctx, _ := wk.Context.Repo(repo.Name)
links := wk.Links
for i, tfInst := range wk.Terraform {
tf := tfInst.Terraform
linkPath := ""
if links != nil {
if path, ok := links.Terraform[tf.Name]; ok {
linkPath = path
}
}
var buf bytes.Buffer
buf.Grow(5 * 1024)
plate := tfInst.Version.ValuesTemplate
if linkPath != "" {
var err error
plate, err = utils.ReadFile(pathing.SanitizeFilepath(filepath.Join(linkPath, "terraform.tfvars")))
if err != nil {
return err
}
}
tmpl, err := template.MakeTemplate(plate)
if err != nil {
return err
}
values := map[string]interface{}{
"Values": ctx,
"Configuration": wk.Context.Configuration,
"Cluster": wk.Provider.Cluster(),
"Project": wk.Provider.Project(),
"Namespace": wk.Config.Namespace(repo.Name),
"Region": wk.Provider.Region(),
"Context": wk.Provider.Context(),
"Config": config.Read(),
"ClusterAPI": wk.Manifest.ClusterAPI,
"Applications": apps,
}
if err := tmpl.Execute(&buf, values); err != nil {
return err
}
module := make(map[string]interface{})
module["name"] = tf.Name
if linkPath != "" {
module["path"] = linkPath
} else {
module["path"] = "./" + tf.Name
}
module["conf"] = buf.String()
if tf.Dependencies != nil && tf.Dependencies.Wirings != nil {
module["deps"] = tf.Dependencies.Wirings.Terraform
} else {
module["deps"] = map[string]interface{}{}
}
module["Manual"] = manualSection(contents, tf.Name)
var moduleBuf bytes.Buffer
moduleBuf.Grow(1024)
if err := template.RenderTemplate(&moduleBuf, moduleTemplate, module); err != nil {
return err
}
modules[i+1] = moduleBuf.String()
valuesFile := pathing.SanitizeFilepath(filepath.Join(scaffold.Root, tf.Name, "terraform.tfvars"))
os.Remove(valuesFile)
moduleBuf.Reset()
buf.Reset()
}
if err := utils.WriteFile(mainFile, []byte(strings.Join(modules, "\n\n"))); err != nil {
return err
}
if err := scaffold.buildOutputs(wk); err != nil {
return err
}
secrets := buildTfSecrets(wk.Terraform)
if err := buildSecrets(pathing.SanitizeFilepath(filepath.Join(scaffold.Root, ".gitattributes")), secrets); err != nil {
return err
}
return nil
}
// TODO: move to some sort of scaffold util?
func (scaffold *Scaffold) untarModules(wk *wkspace.Workspace) error {
length := len(wk.Terraform)
utils.Highlight("unpacking %d %s", len(wk.Terraform), utils.Pluralize("module", "modules", length))
for _, tfInst := range wk.Terraform {
tf := tfInst.Terraform
v := tfInst.Version
path := pathing.SanitizeFilepath(filepath.Join(scaffold.Root, tf.Name))
if err := os.MkdirAll(path, os.ModePerm); err != nil {
fmt.Print("\n")
return err
}
if err := untar(v, tf, path); err != nil {
fmt.Print("\n")
return err
}
fmt.Print(".")
}
utils.Success("\u2713\n")
return nil
}
func (scaffold *Scaffold) buildOutputs(wk *wkspace.Workspace) error {
var buf bytes.Buffer
buf.Grow(5 * 1024)
tmp, err := template.MakeTemplate(outputTemplate)
if err != nil {
return err
}
sort.SliceStable(wk.Terraform, func(i, j int) bool {
return wk.Terraform[i].Terraform.Name < wk.Terraform[j].Terraform.Name
})
for _, tfInst := range wk.Terraform {
tfName := tfInst.Terraform.Name
outs := tfInst.Version.Dependencies.Outputs
outputs := maps.Keys(outs)
sort.Strings(outputs)
for _, name := range outputs {
value := outs[name]
err = tmp.Execute(&buf, map[string]interface{}{"Name": name, "Value": value, "Module": tfName})
if err != nil {
return err
}
buf.WriteString("\n\n")
}
}
outputFile := pathing.SanitizeFilepath(filepath.Join(scaffold.Root, "outputs.tf"))
return utils.WriteFile(outputFile, buf.Bytes())
}
func untar(v *api.Version, tf *api.Terraform, dir string) error {
resp, err := http.Get(v.Package)
if err != nil {
return err
}
return utils.Untar(resp.Body, dir, tf.Name)
}
func manualSection(contents, name string) string {
re := regexp.MustCompile(fmt.Sprintf(`(?s)### BEGIN MANUAL SECTION <<%s>>(.*)### END MANUAL SECTION <<%s>>`, name, name))
matches := re.FindStringSubmatch(contents)
if len(matches) > 0 {
return strings.TrimSpace(matches[1])
}
return ""
}
func buildTfSecrets(installations []*api.TerraformInstallation) []string {
res := []string{}
for _, inst := range installations {
res = append(res, inst.Version.Dependencies.Secrets...)
}
return res
}
func buildContext(wk *wkspace.Workspace, repo string, installations []*api.TerraformInstallation) map[string]interface{} {
ctx := map[string]interface{}{
"Namespace": wk.Config.Namespace(repo),
}
for _, inst := range installations {
for k, v := range inst.Version.Dependencies.ProviderWirings {
if k == "cluster" {
ctx["Cluster"] = v
}
ctx[k] = v
}
}
return ctx
}