-
Notifications
You must be signed in to change notification settings - Fork 76
/
load_hcl.go
345 lines (292 loc) · 10.4 KB
/
load_hcl.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
package tfconfig
import (
"encoding/json"
"fmt"
"strings"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclparse"
ctyjson "github.com/zclconf/go-cty/cty/json"
)
func loadModule(fs FS, dir string) (*Module, Diagnostics) {
mod := newModule(dir)
primaryPaths, diags := dirFiles(fs, dir)
parser := hclparse.NewParser()
for _, filename := range primaryPaths {
var file *hcl.File
var fileDiags hcl.Diagnostics
b, err := fs.ReadFile(filename)
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Failed to read file",
Detail: fmt.Sprintf("The configuration file %q could not be read.", filename),
})
continue
}
if strings.HasSuffix(filename, ".json") {
file, fileDiags = parser.ParseJSON(b, filename)
} else {
file, fileDiags = parser.ParseHCL(b, filename)
}
diags = append(diags, fileDiags...)
if file == nil {
continue
}
content, _, contentDiags := file.Body.PartialContent(rootSchema)
diags = append(diags, contentDiags...)
for _, block := range content.Blocks {
switch block.Type {
case "terraform":
content, _, contentDiags := block.Body.PartialContent(terraformBlockSchema)
diags = append(diags, contentDiags...)
if attr, defined := content.Attributes["required_version"]; defined {
var version string
valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version)
diags = append(diags, valDiags...)
if !valDiags.HasErrors() {
mod.RequiredCore = append(mod.RequiredCore, version)
}
}
for _, innerBlock := range content.Blocks {
switch innerBlock.Type {
case "required_providers":
reqs, reqsDiags := decodeRequiredProvidersBlock(innerBlock)
diags = append(diags, reqsDiags...)
for name, req := range reqs {
if _, exists := mod.RequiredProviders[name]; !exists {
mod.RequiredProviders[name] = req
} else {
if req.Source != "" {
source := mod.RequiredProviders[name].Source
if source != "" && source != req.Source {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Multiple provider source attributes",
Detail: fmt.Sprintf("Found multiple source attributes for provider %s: %q, %q", name, source, req.Source),
Subject: &innerBlock.DefRange,
})
} else {
mod.RequiredProviders[name].Source = req.Source
}
}
mod.RequiredProviders[name].VersionConstraints = append(mod.RequiredProviders[name].VersionConstraints, req.VersionConstraints...)
}
}
}
}
case "variable":
content, _, contentDiags := block.Body.PartialContent(variableSchema)
diags = append(diags, contentDiags...)
name := block.Labels[0]
v := &Variable{
Name: name,
Pos: sourcePosHCL(block.DefRange),
}
mod.Variables[name] = v
if attr, defined := content.Attributes["type"]; defined {
// We handle this particular attribute in a somewhat-tricky way:
// since Terraform may evolve its type expression syntax in
// future versions, we don't want to be overly-strict in how
// we handle it here, and so we'll instead just take the raw
// source provided by the user, using the source location
// information in the expression object.
//
// However, older versions of Terraform expected the type
// to be a string containing a keyword, so we'll need to
// handle that as a special case first for backward compatibility.
var typeExpr string
var typeExprAsStr string
valDiags := gohcl.DecodeExpression(attr.Expr, nil, &typeExprAsStr)
if !valDiags.HasErrors() {
typeExpr = typeExprAsStr
} else {
rng := attr.Expr.Range()
sourceFilename := rng.Filename
source, exists := parser.Sources()[sourceFilename]
if exists {
typeExpr = string(rng.SliceBytes(source))
} else {
// This should never happen, so we'll just warn about it and leave the type unspecified.
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Source code not available",
Detail: fmt.Sprintf("Source code is not available for the file %q, which declares the variable %q.", sourceFilename, name),
Subject: &block.DefRange,
})
typeExpr = ""
}
}
v.Type = typeExpr
}
if attr, defined := content.Attributes["description"]; defined {
var description string
valDiags := gohcl.DecodeExpression(attr.Expr, nil, &description)
diags = append(diags, valDiags...)
v.Description = description
}
if attr, defined := content.Attributes["default"]; defined {
// To avoid the caller needing to deal with cty here, we'll
// use its JSON encoding to convert into an
// approximately-equivalent plain Go interface{} value
// to return.
val, valDiags := attr.Expr.Value(nil)
diags = append(diags, valDiags...)
if val.IsWhollyKnown() { // should only be false if there are errors in the input
valJSON, err := ctyjson.Marshal(val, val.Type())
if err != nil {
// Should never happen, since all possible known
// values have a JSON mapping.
panic(fmt.Errorf("failed to serialize default value as JSON: %s", err))
}
var def interface{}
err = json.Unmarshal(valJSON, &def)
if err != nil {
// Again should never happen, because valJSON is
// guaranteed valid by ctyjson.Marshal.
panic(fmt.Errorf("failed to re-parse default value from JSON: %s", err))
}
v.Default = def
}
} else {
v.Required = true
}
case "output":
content, _, contentDiags := block.Body.PartialContent(outputSchema)
diags = append(diags, contentDiags...)
name := block.Labels[0]
o := &Output{
Name: name,
Pos: sourcePosHCL(block.DefRange),
}
mod.Outputs[name] = o
if attr, defined := content.Attributes["description"]; defined {
var description string
valDiags := gohcl.DecodeExpression(attr.Expr, nil, &description)
diags = append(diags, valDiags...)
o.Description = description
}
case "provider":
content, _, contentDiags := block.Body.PartialContent(providerConfigSchema)
diags = append(diags, contentDiags...)
name := block.Labels[0]
// Even if there isn't an explicit version required, we still
// need an entry in our map to signal the unversioned dependency.
if _, exists := mod.RequiredProviders[name]; !exists {
mod.RequiredProviders[name] = &ProviderRequirement{}
}
if attr, defined := content.Attributes["version"]; defined {
var version string
valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version)
diags = append(diags, valDiags...)
if !valDiags.HasErrors() {
mod.RequiredProviders[name].VersionConstraints = append(mod.RequiredProviders[name].VersionConstraints, version)
}
}
case "resource", "data":
content, _, contentDiags := block.Body.PartialContent(resourceSchema)
diags = append(diags, contentDiags...)
typeName := block.Labels[0]
name := block.Labels[1]
r := &Resource{
Type: typeName,
Name: name,
Pos: sourcePosHCL(block.DefRange),
}
var resourcesMap map[string]*Resource
switch block.Type {
case "resource":
r.Mode = ManagedResourceMode
resourcesMap = mod.ManagedResources
case "data":
r.Mode = DataResourceMode
resourcesMap = mod.DataResources
}
key := r.MapKey()
resourcesMap[key] = r
if attr, defined := content.Attributes["provider"]; defined {
// New style here is to provide this as a naked traversal
// expression, but we also support quoted references for
// older configurations that predated this convention.
traversal, travDiags := hcl.AbsTraversalForExpr(attr.Expr)
if travDiags.HasErrors() {
traversal = nil // in case we got any partial results
// Fall back on trying to parse as a string
var travStr string
valDiags := gohcl.DecodeExpression(attr.Expr, nil, &travStr)
if !valDiags.HasErrors() {
var strDiags hcl.Diagnostics
traversal, strDiags = hclsyntax.ParseTraversalAbs([]byte(travStr), "", hcl.Pos{})
if strDiags.HasErrors() {
traversal = nil
}
}
}
// If we get out here with a nil traversal then we didn't
// succeed in processing the input.
if len(traversal) > 0 {
providerName := traversal.RootName()
alias := ""
if len(traversal) > 1 {
if getAttr, ok := traversal[1].(hcl.TraverseAttr); ok {
alias = getAttr.Name
}
}
r.Provider = ProviderRef{
Name: providerName,
Alias: alias,
}
} else {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid provider reference",
Detail: "Provider argument requires a provider name followed by an optional alias, like \"aws.foo\".",
Subject: attr.Expr.Range().Ptr(),
})
}
} else {
// If provider _isn't_ set then we'll infer it from the
// resource type.
r.Provider = ProviderRef{
Name: resourceTypeDefaultProviderName(r.Type),
}
}
case "module":
content, _, contentDiags := block.Body.PartialContent(moduleCallSchema)
diags = append(diags, contentDiags...)
name := block.Labels[0]
mc := &ModuleCall{
Name: block.Labels[0],
Pos: sourcePosHCL(block.DefRange),
}
// check if this is overriding an existing module
var origSource string
if origMod, exists := mod.ModuleCalls[name]; exists {
origSource = origMod.Source
}
mod.ModuleCalls[name] = mc
if attr, defined := content.Attributes["source"]; defined {
var source string
valDiags := gohcl.DecodeExpression(attr.Expr, nil, &source)
diags = append(diags, valDiags...)
mc.Source = source
}
if mc.Source == "" {
mc.Source = origSource
}
if attr, defined := content.Attributes["version"]; defined {
var version string
valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version)
diags = append(diags, valDiags...)
mc.Version = version
}
default:
// Should never happen because our cases above should be
// exhaustive for our schema.
panic(fmt.Errorf("unhandled block type %q", block.Type))
}
}
}
return mod, diagnosticsHCL(diags)
}