forked from gruntwork-io/terragrunt
-
Notifications
You must be signed in to change notification settings - Fork 2
/
extension_import_variables.go
275 lines (238 loc) · 8.3 KB
/
extension_import_variables.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
package config
import (
"fmt"
"github.com/coveo/gotemplate/hcl"
"github.com/coveo/gotemplate/utils"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/gruntwork-io/terragrunt/options"
"github.com/gruntwork-io/terragrunt/util"
)
type ImportVariables struct {
TerragruntExtensionBase `hcl:",squash"`
Source string `hcl:"source"`
Vars []string `hcl:"vars"`
RequiredVarFiles []string `hcl:"required_var_files"`
OptionalVarFiles []string `hcl:"optional_var_files"`
NestedUnder string `hcl:"nested_under"`
TFVariablesFile string `hcl:"output_variables_file"`
FlattenLevels *int `hcl:"flatten_levels"`
}
func (item ImportVariables) itemType() (result string) {
return ImportVariablesList{}.argName()
}
func (item ImportVariables) help() (result string) {
if item.Description != "" {
result += fmt.Sprintf("\n%s\n", item.Description)
}
return
}
// ----------------------- ImportVariablesList -----------------------
//go:generate genny -in=extension_base_list.go -out=generated_import_variables.go gen "GenericItem=ImportVariables"
func (list ImportVariablesList) argName() string { return "import_variables" }
func (list ImportVariablesList) sort() ImportVariablesList { return list }
// Merge elements from an imported list to the current list
func (list *ImportVariablesList) Merge(imported ImportVariablesList) {
list.merge(imported, mergeModePrepend, list.argName())
}
func (list ImportVariablesList) CreatesVariableFile() bool {
for _, item := range list.Enabled() {
if item.TFVariablesFile != "" {
return true
}
}
return false
}
func (list ImportVariablesList) Import() (err error) {
if len(list) == 0 {
return nil
}
config := IImportVariables(&list[0]).config()
terragruntOptions := config.options
variablesFiles := make(map[string]map[string]interface{})
for _, item := range list.Enabled() {
item.logger().Debugf("Processing import variables statement %s", item.id())
if item.TFVariablesFile != "" {
if _, ok := variablesFiles[item.TFVariablesFile]; !ok {
variablesFiles[item.TFVariablesFile] = make(map[string]interface{})
}
}
folders := []string{terragruntOptions.WorkingDir}
if item.Source != "" {
newSource, err := config.GetSourceFolder(item.Name, item.Source, len(item.RequiredVarFiles) > 0)
if err != nil {
return err
} else if newSource == "" {
continue
}
folders = []string{newSource}
}
// We first process all the -var because they have precedence over -var-file
// If vars is specified, add -var <key=value> for each specified key
keyFunc := func(key string) string { return strings.Split(key, "=")[0] }
varList := util.RemoveDuplicatesFromList(item.Vars, true, keyFunc)
for _, varDef := range varList {
varDef = SubstituteVars(varDef, terragruntOptions)
var (
key string
value interface{}
)
if !strings.Contains(varDef, "=") {
key = varDef
value = nil
} else {
if key, value, err = util.SplitEnvVariable(varDef); err != nil {
terragruntOptions.Logger.Warningf("-var ignored in %v: %v", item.Name, err)
continue
}
}
if util.ListContainsElement(terragruntOptions.VariablesExplicitlyProvided(), key) {
continue
}
if variablesFiles[item.TFVariablesFile], err = loadVariables(terragruntOptions, &item, variablesFiles[item.TFVariablesFile], map[string]interface{}{key: value}, options.VarParameter); err != nil {
return err
}
}
// If RequiredVarFiles is specified, add -var-file=<file> for each specified files
for _, pattern := range util.RemoveDuplicatesFromListKeepLast(item.RequiredVarFiles) {
pattern = SubstituteVars(pattern, terragruntOptions)
files := config.globFiles(pattern, folders...)
if len(files) == 0 {
return fmt.Errorf("%s: No file matches %s", item.name(), pattern)
}
for _, file := range files {
if variablesFiles[item.TFVariablesFile], err = loadVariablesFromFile(terragruntOptions, &item, file, variablesFiles[item.TFVariablesFile]); err != nil {
return err
}
}
}
// If OptionalVarFiles is specified, check for each file if it exists and if so, add -var-file=<file>
// It is possible that many files resolve to the same path, so we remove duplicates.
for _, pattern := range util.RemoveDuplicatesFromListKeepLast(item.OptionalVarFiles) {
pattern = SubstituteVars(pattern, terragruntOptions)
for _, file := range config.globFiles(pattern, folders...) {
if util.FileExists(file) {
if variablesFiles[item.TFVariablesFile], err = loadVariablesFromFile(terragruntOptions, &item, file, variablesFiles[item.TFVariablesFile]); err != nil {
return err
}
} else {
terragruntOptions.Logger.Debugf("Skipping var-file %s as it does not exist", file)
}
}
}
}
for fileName, variables := range variablesFiles {
if len(variables) == 0 {
continue
}
if err := filepath.Walk(terragruntOptions.WorkingDir, func(walkPath string, info os.FileInfo, err error) error {
if !info.IsDir() {
return nil
}
filesInDir, err := ioutil.ReadDir(walkPath)
if err != nil {
return err
}
for _, dirFile := range filesInDir {
if filepath.Ext(dirFile.Name()) == ".tf" {
terragruntOptions.Logger.Info("Writing terraform variables to directory: " + walkPath)
writeTerraformVariables(path.Join(walkPath, fileName), variables)
break
}
}
return nil
}); err != nil {
return err
}
}
return nil
}
func loadVariablesFromFile(terragruntOptions *options.TerragruntOptions, importOptions *ImportVariables, file string, currentVariables map[string]interface{}) (map[string]interface{}, error) {
terragruntOptions.Logger.Info("Importing", file)
vars, err := terragruntOptions.LoadVariablesFromFile(file)
if err != nil {
return nil, err
}
return loadVariables(terragruntOptions, importOptions, currentVariables, vars, options.VarFile)
}
func loadVariables(terragruntOptions *options.TerragruntOptions, importOptions *ImportVariables, currentVariables map[string]interface{}, newVariables map[string]interface{}, source options.VariableSource) (map[string]interface{}, error) {
if importOptions.NestedUnder != "" {
newVariables = map[string]interface{}{importOptions.NestedUnder: newVariables}
}
terragruntOptions.ImportVariablesMap(newVariables, source)
flattenLevels := -1 // flatten all
if importOptions.FlattenLevels != nil {
flattenLevels = *importOptions.FlattenLevels
}
if currentVariables != nil {
return utils.MergeDictionaries(flatten(newVariables, "", flattenLevels), currentVariables)
}
return nil, nil
}
func writeTerraformVariables(fileName string, variables map[string]interface{}) {
if variables == nil {
return
}
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer f.Close()
lines := []string{}
for key, value := range variables {
lines = append(lines, fmt.Sprintf("variable \"%s\" {\n", key))
if value != nil {
terraformValue := map[string]interface{}{"default": value}
if _, isMap := value.(map[string]interface{}); isMap {
terraformValue["type"] = "map"
} else if _, isList := value.([]interface{}); isList {
terraformValue["type"] = "list"
}
variableContent, err := hcl.Marshal(terraformValue)
if err != nil {
panic(err)
}
lines = append(lines, string(variableContent))
}
lines = append(lines, "}\n\n")
}
for _, line := range lines {
if _, err = f.WriteString(line); err != nil {
panic(err)
}
}
}
func flatten(nestedMap map[string]interface{}, prefix string, numberOfLevels int) map[string]interface{} {
keysToRemove := []string{}
itemsToAdd := make(map[string]interface{})
for key, value := range nestedMap {
if valueMap, ok := value.(map[string]interface{}); ok {
isTopLevel := true
for _, childValue := range valueMap {
if _, childIsMap := childValue.(map[string]interface{}); childIsMap {
isTopLevel = false
}
}
if (numberOfLevels < 0 && !isTopLevel) || numberOfLevels >= 1 {
keysToRemove = append(keysToRemove, key)
for key, value := range flatten(valueMap, key+"_", numberOfLevels-1) {
itemsToAdd[key] = value
}
}
}
}
for _, key := range keysToRemove {
delete(nestedMap, key)
}
for key, value := range itemsToAdd {
nestedMap[key] = value
}
newMap := make(map[string]interface{})
for key, value := range nestedMap {
newMap[prefix+key] = value
}
return newMap
}