/
templatevariables.go
274 lines (236 loc) · 6.89 KB
/
templatevariables.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
package cli
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"golang.org/x/xerrors"
"gopkg.in/yaml.v3"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/zclconf/go-cty/cty"
"github.com/coder/coder/v2/codersdk"
)
/**
* DiscoverVarsFiles function loads vars files in a predefined order:
* 1. terraform.tfvars
* 2. terraform.tfvars.json
* 3. *.auto.tfvars
* 4. *.auto.tfvars.json
*/
func DiscoverVarsFiles(workDir string) ([]string, error) {
var found []string
fi, err := os.Stat(filepath.Join(workDir, "terraform.tfvars"))
if err == nil {
found = append(found, filepath.Join(workDir, fi.Name()))
} else if !os.IsNotExist(err) {
return nil, err
}
fi, err = os.Stat(filepath.Join(workDir, "terraform.tfvars.json"))
if err == nil {
found = append(found, filepath.Join(workDir, fi.Name()))
} else if !os.IsNotExist(err) {
return nil, err
}
dirEntries, err := os.ReadDir(workDir)
if err != nil {
return nil, err
}
for _, dirEntry := range dirEntries {
if strings.HasSuffix(dirEntry.Name(), ".auto.tfvars") || strings.HasSuffix(dirEntry.Name(), ".auto.tfvars.json") {
found = append(found, filepath.Join(workDir, dirEntry.Name()))
}
}
return found, nil
}
func ParseUserVariableValues(varsFiles []string, variablesFile string, commandLineVariables []string) ([]codersdk.VariableValue, error) {
fromVars, err := parseVariableValuesFromVarsFiles(varsFiles)
if err != nil {
return nil, err
}
fromFile, err := parseVariableValuesFromFile(variablesFile)
if err != nil {
return nil, err
}
fromCommandLine, err := parseVariableValuesFromCommandLine(commandLineVariables)
if err != nil {
return nil, err
}
return combineVariableValues(fromVars, fromFile, fromCommandLine), nil
}
func parseVariableValuesFromVarsFiles(varsFiles []string) ([]codersdk.VariableValue, error) {
var parsed []codersdk.VariableValue
for _, varsFile := range varsFiles {
content, err := os.ReadFile(varsFile)
if err != nil {
return nil, err
}
var t []codersdk.VariableValue
ext := filepath.Ext(varsFile)
switch ext {
case ".tfvars":
t, err = parseVariableValuesFromHCL(content)
if err != nil {
return nil, xerrors.Errorf("unable to parse HCL content: %w", err)
}
case ".json":
t, err = parseVariableValuesFromJSON(content)
if err != nil {
return nil, xerrors.Errorf("unable to parse JSON content: %w", err)
}
default:
return nil, xerrors.Errorf("unexpected tfvars format: %s", ext)
}
parsed = append(parsed, t...)
}
return parsed, nil
}
func parseVariableValuesFromHCL(content []byte) ([]codersdk.VariableValue, error) {
parser := hclparse.NewParser()
hclFile, diags := parser.ParseHCL(content, "file.hcl")
if diags.HasErrors() {
return nil, diags
}
attrs, diags := hclFile.Body.JustAttributes()
if diags.HasErrors() {
return nil, diags
}
stringData := map[string]string{}
for _, attribute := range attrs {
ctyValue, diags := attribute.Expr.Value(nil)
if diags.HasErrors() {
return nil, diags
}
ctyType := ctyValue.Type()
if ctyType.Equals(cty.String) {
stringData[attribute.Name] = ctyValue.AsString()
} else if ctyType.Equals(cty.Number) {
stringData[attribute.Name] = ctyValue.AsBigFloat().String()
} else if ctyType.IsTupleType() {
// In case of tuples, Coder only supports the list(string) type.
var items []string
var err error
_ = ctyValue.ForEachElement(func(key, val cty.Value) (stop bool) {
if !val.Type().Equals(cty.String) {
err = xerrors.Errorf("unsupported tuple item type: %s ", val.GoString())
return true
}
items = append(items, val.AsString())
return false
})
if err != nil {
return nil, err
}
m, err := json.Marshal(items)
if err != nil {
return nil, err
}
stringData[attribute.Name] = string(m)
} else {
return nil, xerrors.Errorf("unsupported value type (name: %s): %s", attribute.Name, ctyType.GoString())
}
}
return convertMapIntoVariableValues(stringData), nil
}
// parseVariableValuesFromJSON converts the .tfvars.json content into template variables.
// The function visits only root-level properties as template variables do not support nested
// structures.
func parseVariableValuesFromJSON(content []byte) ([]codersdk.VariableValue, error) {
var data map[string]interface{}
err := json.Unmarshal(content, &data)
if err != nil {
return nil, err
}
stringData := map[string]string{}
for key, value := range data {
switch value.(type) {
case string, int, bool:
stringData[key] = fmt.Sprintf("%v", value)
default:
m, err := json.Marshal(value)
if err != nil {
return nil, err
}
stringData[key] = string(m)
}
}
return convertMapIntoVariableValues(stringData), nil
}
func convertMapIntoVariableValues(m map[string]string) []codersdk.VariableValue {
var parsed []codersdk.VariableValue
for key, value := range m {
parsed = append(parsed, codersdk.VariableValue{
Name: key,
Value: value,
})
}
sort.Slice(parsed, func(i, j int) bool {
return parsed[i].Name < parsed[j].Name
})
return parsed
}
func parseVariableValuesFromFile(variablesFile string) ([]codersdk.VariableValue, error) {
var values []codersdk.VariableValue
if variablesFile == "" {
return values, nil
}
variablesMap, err := createVariablesMapFromFile(variablesFile)
if err != nil {
return nil, err
}
for name, value := range variablesMap {
values = append(values, codersdk.VariableValue{
Name: name,
Value: value,
})
}
return values, nil
}
// Reads a YAML file and populates a string -> string map.
// Throws an error if the file name is empty.
func createVariablesMapFromFile(variablesFile string) (map[string]string, error) {
if variablesFile == "" {
return nil, xerrors.Errorf("variable file name is not specified")
}
variablesMap := make(map[string]string)
variablesFileContents, err := os.ReadFile(variablesFile)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(variablesFileContents, &variablesMap)
if err != nil {
return nil, err
}
return variablesMap, nil
}
func parseVariableValuesFromCommandLine(variables []string) ([]codersdk.VariableValue, error) {
var values []codersdk.VariableValue
for _, keyValue := range variables {
split := strings.SplitN(keyValue, "=", 2)
if len(split) < 2 {
return nil, xerrors.Errorf("format key=value expected, but got %s", keyValue)
}
values = append(values, codersdk.VariableValue{
Name: split[0],
Value: split[1],
})
}
return values, nil
}
func combineVariableValues(valuesSets ...[]codersdk.VariableValue) []codersdk.VariableValue {
combinedValues := make(map[string]string)
for _, values := range valuesSets {
for _, v := range values {
combinedValues[v.Name] = v.Value
}
}
var result []codersdk.VariableValue
for name, value := range combinedValues {
result = append(result, codersdk.VariableValue{Name: name, Value: value})
}
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result
}