/
terraform_generate_backend.go
90 lines (71 loc) 路 2.16 KB
/
terraform_generate_backend.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
package exec
import (
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"path"
cfg "github.com/cloudposse/atmos/pkg/config"
u "github.com/cloudposse/atmos/pkg/utils"
)
// ExecuteTerraformGenerateBackendCmd executes `terraform generate backend` command
func ExecuteTerraformGenerateBackendCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("invalid arguments. The command requires one argument `component`")
}
flags := cmd.Flags()
stack, err := flags.GetString("stack")
if err != nil {
return err
}
component := args[0]
info, err := processCommandLineArgs("terraform", cmd, args)
if err != nil {
return err
}
info.ComponentFromArg = component
info.Stack = stack
info.ComponentType = "terraform"
cliConfig, err := cfg.InitCliConfig(info, true)
if err != nil {
return err
}
info, err = ProcessStacks(cliConfig, info, true)
if err != nil {
return err
}
if info.ComponentBackendType == "" {
return fmt.Errorf("\n'backend_type' is missing for the '%s' component.\n", component)
}
if info.ComponentBackendSection == nil {
return fmt.Errorf("\nCould not find 'backend' config for the '%s' component.\n", component)
}
componentBackendConfig := generateComponentBackendConfig(info.ComponentBackendType, info.ComponentBackendSection)
u.PrintInfoVerbose(cliConfig.Logs.Verbose, "Component backend config:\n\n")
err = u.PrintAsJSON(componentBackendConfig)
if err != nil {
return err
}
// Check if the `backend` section has `workspace_key_prefix`
if _, ok := info.ComponentBackendSection["workspace_key_prefix"].(string); !ok {
return fmt.Errorf("\nBackend config for the '%s' component is missing 'workspace_key_prefix'\n", component)
}
// Write backend config to file
var backendFilePath = path.Join(
cliConfig.BasePath,
cliConfig.Components.Terraform.BasePath,
info.ComponentFolderPrefix,
info.FinalComponent,
"backend.tf.json",
)
fmt.Println()
u.PrintInfo("Writing the backend config to file:")
u.PrintMessage(backendFilePath)
if !info.DryRun {
err = u.WriteToFileAsJSON(backendFilePath, componentBackendConfig, 0644)
if err != nil {
return err
}
}
fmt.Println()
return nil
}