-
-
Notifications
You must be signed in to change notification settings - Fork 91
/
terraform.go
428 lines (369 loc) · 13.1 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package exec
import (
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"os"
"path"
"strings"
cfg "github.com/cloudposse/atmos/pkg/config"
u "github.com/cloudposse/atmos/pkg/utils"
)
const (
autoApproveFlag = "-auto-approve"
outFlag = "-out"
varFileFlag = "-var-file"
)
// ExecuteTerraformCmd parses the provided arguments and flags and executes terraform commands
func ExecuteTerraformCmd(cmd *cobra.Command, args []string) error {
info, err := processCommandLineArgs("terraform", cmd, args)
if err != nil {
return err
}
return ExecuteTerraform(info)
}
// ExecuteTerraform executes terraform commands
func ExecuteTerraform(info cfg.ConfigAndStacksInfo) error {
cliConfig, err := cfg.InitCliConfig(info, true)
if err != nil {
return err
}
if info.NeedHelp {
return nil
}
info, err = ProcessStacks(cliConfig, info, true)
if err != nil {
return err
}
if len(info.Stack) < 1 {
return errors.New("stack must be specified")
}
err = checkTerraformConfig(cliConfig)
if err != nil {
return err
}
// Check if the component (or base component) exists as Terraform component
componentPath := path.Join(cliConfig.TerraformDirAbsolutePath, info.ComponentFolderPrefix, info.FinalComponent)
componentPathExists, err := u.IsDirectory(componentPath)
if err != nil || !componentPathExists {
return fmt.Errorf("'%s' points to the Terraform component '%s', but it does not exist in '%s'",
info.ComponentFromArg,
info.FinalComponent,
path.Join(cliConfig.Components.Terraform.BasePath, info.ComponentFolderPrefix),
)
}
// Check if the component is allowed to be provisioned (`metadata.type` attribute is not set to `abstract`)
if (info.SubCommand == "plan" || info.SubCommand == "apply" || info.SubCommand == "deploy" || info.SubCommand == "workspace") && info.ComponentIsAbstract {
return fmt.Errorf("abstract component '%s' cannot be provisioned since it's explicitly prohibited from being deployed "+
"by 'metadata.type: abstract' attribute", path.Join(info.ComponentFolderPrefix, info.Component))
}
varFile := constructTerraformComponentVarfileName(info)
planFile := constructTerraformComponentPlanfileName(info)
if info.SubCommand == "clean" {
fmt.Println("Deleting '.terraform' folder")
err = os.RemoveAll(path.Join(componentPath, ".terraform"))
if err != nil {
u.PrintError(err)
}
fmt.Println("Deleting '.terraform.lock.hcl' file")
_ = os.Remove(path.Join(componentPath, ".terraform.lock.hcl"))
fmt.Printf("Deleting terraform varfile: %s\n", varFile)
_ = os.Remove(path.Join(componentPath, varFile))
fmt.Printf("Deleting terraform planfile: %s\n", planFile)
_ = os.Remove(path.Join(componentPath, planFile))
// If `auto_generate_backend_file` is `true` (we are auto-generating backend files), remove `backend.tf.json`
if cliConfig.Components.Terraform.AutoGenerateBackendFile {
fmt.Println("Deleting 'backend.tf.json' file")
_ = os.Remove(path.Join(componentPath, "backend.tf.json"))
}
tfDataDir := os.Getenv("TF_DATA_DIR")
if len(tfDataDir) > 0 && tfDataDir != "." && tfDataDir != "/" && tfDataDir != "./" {
u.PrintInfo(fmt.Sprintf("Found ENV var TF_DATA_DIR=%s", tfDataDir))
var userAnswer string
fmt.Printf("Do you want to delete the folder '%s'? (only 'yes' will be accepted to approve)\n", tfDataDir)
fmt.Print("Enter a value: ")
count, err := fmt.Scanln(&userAnswer)
if count > 0 && err != nil {
return err
}
if userAnswer == "yes" {
fmt.Printf("Deleting folder '%s'\n", tfDataDir)
err = os.RemoveAll(path.Join(componentPath, tfDataDir))
if err != nil {
u.PrintError(err)
}
}
}
fmt.Println()
return nil
}
// Print component variables and write to file
// Don't process variables when executing `terraform workspace` commands
if info.SubCommand != "workspace" {
u.PrintInfo(fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':\n", info.ComponentFromArg, info.Stack))
err = u.PrintAsYAML(info.ComponentVarsSection)
if err != nil {
return err
}
// Write variables to a file (only if we are not using the previously generated terraform plan)
if !info.UseTerraformPlan {
var varFilePath, varFileNameFromArg string
// Handle `terraform varfile` and `terraform write varfile` legacy commands
if info.SubCommand == "varfile" || (info.SubCommand == "write" && info.SubCommand2 == "varfile") {
if len(info.AdditionalArgsAndFlags) == 2 {
fileFlag := info.AdditionalArgsAndFlags[0]
if fileFlag == "-f" || fileFlag == "--file" {
varFileNameFromArg = info.AdditionalArgsAndFlags[1]
}
}
}
if len(varFileNameFromArg) > 0 {
varFilePath = varFileNameFromArg
} else {
varFilePath = constructTerraformComponentVarfilePath(cliConfig, info)
}
u.PrintInfo("Writing the variables to file:")
fmt.Println(varFilePath)
if !info.DryRun {
err = u.WriteToFileAsJSON(varFilePath, info.ComponentVarsSection, 0644)
if err != nil {
return err
}
}
}
}
// Handle `terraform varfile` and `terraform write varfile` legacy commands
if info.SubCommand == "varfile" || (info.SubCommand == "write" && info.SubCommand2 == "varfile") {
fmt.Println()
return nil
}
// Check if component 'settings.validation' section is specified and validate the component
valid, err := ValidateComponent(cliConfig, info.ComponentFromArg, info.ComponentSection, "", "")
if err != nil {
return err
}
if !valid {
return fmt.Errorf("\nComponent '%s' did not pass the validation policies.\n", info.ComponentFromArg)
}
// Auto generate backend file
if cliConfig.Components.Terraform.AutoGenerateBackendFile {
backendFileName := path.Join(
constructTerraformComponentWorkingDir(cliConfig, info),
"backend.tf.json",
)
u.PrintInfo("Writing the backend config to file:")
fmt.Println(backendFileName)
if !info.DryRun {
var componentBackendConfig = generateComponentBackendConfig(info.ComponentBackendType, info.ComponentBackendSection)
err = u.WriteToFileAsJSON(backendFileName, componentBackendConfig, 0644)
if err != nil {
return err
}
}
}
// Run `terraform init` before running other commands
runTerraformInit := true
if info.SubCommand == "init" ||
info.SubCommand == "clean" ||
(info.SubCommand == "deploy" && !cliConfig.Components.Terraform.DeployRunInit) {
runTerraformInit = false
}
if info.SkipInit {
fmt.Println()
u.PrintInfo("Skipping over 'terraform init' due to '--skip-init' flag being passed")
runTerraformInit = false
}
if runTerraformInit {
initCommandWithArguments := []string{"init"}
if info.SubCommand == "workspace" || cliConfig.Components.Terraform.InitRunReconfigure {
initCommandWithArguments = []string{"init", "-reconfigure"}
}
err = ExecuteShellCommand(
info.Command,
initCommandWithArguments,
componentPath,
info.ComponentEnvList,
info.DryRun,
true,
info.RedirectStdErr,
)
if err != nil {
return err
}
}
// Handle `terraform deploy` custom command
if info.SubCommand == "deploy" {
info.SubCommand = "apply"
if !info.UseTerraformPlan && !u.SliceContainsString(info.AdditionalArgsAndFlags, autoApproveFlag) {
info.AdditionalArgsAndFlags = append(info.AdditionalArgsAndFlags, autoApproveFlag)
}
}
// Handle cliConfig.Components.Terraform.ApplyAutoApprove flag
if info.SubCommand == "apply" && cliConfig.Components.Terraform.ApplyAutoApprove && !info.UseTerraformPlan {
if !u.SliceContainsString(info.AdditionalArgsAndFlags, autoApproveFlag) {
info.AdditionalArgsAndFlags = append(info.AdditionalArgsAndFlags, autoApproveFlag)
}
}
// Print command info
u.PrintInfo("\nCommand info:")
fmt.Println("Terraform binary: " + info.Command)
if info.SubCommand2 == "" {
fmt.Printf("Terraform command: %s\n", info.SubCommand)
} else {
fmt.Printf("Terraform command: %s %s\n", info.SubCommand, info.SubCommand2)
}
fmt.Printf("Arguments and flags: %v\n", info.AdditionalArgsAndFlags)
fmt.Println("Component: " + info.ComponentFromArg)
if len(info.BaseComponentPath) > 0 {
fmt.Println("Terraform component: " + info.BaseComponentPath)
}
if len(info.ComponentInheritanceChain) > 0 {
fmt.Println("Inheritance: " + info.ComponentFromArg + " -> " + strings.Join(info.ComponentInheritanceChain, " -> "))
}
if info.Stack == info.StackFromArg {
fmt.Println("Stack: " + info.StackFromArg)
} else {
fmt.Println("Stack: " + info.StackFromArg)
fmt.Println("Stack path: " + path.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath, info.Stack))
}
workingDir := constructTerraformComponentWorkingDir(cliConfig, info)
fmt.Printf("Working dir: %s\n", workingDir)
// Print ENV vars if they are found in the component's stack config
if len(info.ComponentEnvList) > 0 {
fmt.Println()
u.PrintInfo("Using ENV vars:")
for _, v := range info.ComponentEnvList {
fmt.Println(v)
}
}
allArgsAndFlags := strings.Fields(info.SubCommand)
switch info.SubCommand {
case "plan":
// Add varfile
allArgsAndFlags = append(allArgsAndFlags, []string{varFileFlag, varFile}...)
// Add planfile
if !u.SliceContainsString(info.AdditionalArgsAndFlags, outFlag) &&
!u.SliceContainsStringHasPrefix(info.AdditionalArgsAndFlags, outFlag+"=") {
allArgsAndFlags = append(allArgsAndFlags, []string{outFlag, planFile}...)
}
case "destroy":
allArgsAndFlags = append(allArgsAndFlags, []string{varFileFlag, varFile}...)
case "import":
allArgsAndFlags = append(allArgsAndFlags, []string{varFileFlag, varFile}...)
case "refresh":
allArgsAndFlags = append(allArgsAndFlags, []string{varFileFlag, varFile}...)
case "apply":
if info.UseTerraformPlan {
if info.PlanFile != "" {
// If the planfile name was passed on the command line, use it
allArgsAndFlags = append(allArgsAndFlags, []string{info.PlanFile}...)
} else {
// Otherwise, use the planfile name what is autogenerated by Atmos
allArgsAndFlags = append(allArgsAndFlags, []string{planFile}...)
}
} else {
allArgsAndFlags = append(allArgsAndFlags, []string{varFileFlag, varFile}...)
}
case "init":
if cliConfig.Components.Terraform.InitRunReconfigure {
allArgsAndFlags = append(allArgsAndFlags, []string{"-reconfigure"}...)
}
case "workspace":
if info.SubCommand2 == "list" || info.SubCommand2 == "show" {
allArgsAndFlags = append(allArgsAndFlags, []string{info.SubCommand2}...)
} else if info.SubCommand2 != "" {
allArgsAndFlags = append(allArgsAndFlags, []string{info.SubCommand2, info.TerraformWorkspace}...)
}
}
allArgsAndFlags = append(allArgsAndFlags, info.AdditionalArgsAndFlags...)
// Run `terraform workspace` before executing other terraform commands
if info.SubCommand != "init" && !(info.SubCommand == "workspace" && info.SubCommand2 != "") {
workspaceSelectRedirectStdErr := "/dev/stdout"
// If `--redirect-stderr` flag is not passed, always redirect `stderr` to `stdout` for `terraform workspace select` command
if info.RedirectStdErr != "" {
workspaceSelectRedirectStdErr = info.RedirectStdErr
}
err = ExecuteShellCommand(
info.Command,
[]string{"workspace", "select", info.TerraformWorkspace},
componentPath,
info.ComponentEnvList,
info.DryRun,
true,
workspaceSelectRedirectStdErr,
)
if err != nil {
err = ExecuteShellCommand(
info.Command,
[]string{"workspace", "new", info.TerraformWorkspace},
componentPath,
info.ComponentEnvList,
info.DryRun,
true,
info.RedirectStdErr,
)
if err != nil {
return err
}
}
}
// Check if the terraform command requires a user interaction,
// but it's running in a scripted environment (where a `tty` is not attached or `stdin` is not attached)
if os.Stdin == nil && !u.SliceContainsString(info.AdditionalArgsAndFlags, autoApproveFlag) {
errorMessage := ""
if info.SubCommand == "apply" {
errorMessage = "'terraform apply' requires a user interaction, but it's running without `tty` or `stdin` attached." +
"\nUse 'terraform apply -auto-approve' or 'terraform deploy' instead."
}
if errorMessage != "" {
return errors.New(errorMessage)
}
}
// Check `region` for `terraform import`
if info.SubCommand == "import" {
if region, regionExist := info.ComponentVarsSection["region"].(string); regionExist {
info.ComponentEnvList = append(info.ComponentEnvList, fmt.Sprintf("AWS_REGION=%s", region))
}
}
// Execute `terraform shell` command
if info.SubCommand == "shell" {
err = execTerraformShellCommand(
info.ComponentFromArg,
info.Stack,
info.ComponentEnvList,
varFile,
workingDir,
info.TerraformWorkspace,
componentPath,
)
if err != nil {
return err
}
return nil
}
// Execute the provided command (except for `terraform workspace` which was executed above)
if !(info.SubCommand == "workspace" && info.SubCommand2 == "") {
err = ExecuteShellCommand(
info.Command,
allArgsAndFlags,
componentPath,
info.ComponentEnvList,
info.DryRun,
true,
info.RedirectStdErr,
)
if err != nil {
return err
}
}
// Clean up
if info.SubCommand != "plan" && info.PlanFile == "" {
planFilePath := constructTerraformComponentPlanfilePath(cliConfig, info)
_ = os.Remove(planFilePath)
}
if info.SubCommand == "apply" {
varFilePath := constructTerraformComponentVarfilePath(cliConfig, info)
_ = os.Remove(varFilePath)
}
return nil
}