Debian Codegraph @

tfconfig/load_hcl.go

raw
1 // Copyright (c) HashiCorp, Inc.
2 // SPDX-License-Identifier: MPL-2.0
3
4 package tfconfig
5
6 import (
7 "encoding/json"
8 "fmt"
9 "strings"
10
11 "github.com/hashicorp/hcl/v2/hclsyntax"
12
13 "github.com/hashicorp/hcl/v2"
14 "github.com/hashicorp/hcl/v2/gohcl"
15 "github.com/hashicorp/hcl/v2/hclparse"
16 ctyjson "github.com/zclconf/go-cty/cty/json"
17 )
18
19 func loadModule(fs FS, dir string) (*Module, Diagnostics) {
20 mod := NewModule(dir)
21 primaryPaths, diags := dirFiles(fs, dir)
22
23 parser := hclparse.NewParser()
24
25 for _, filename := range primaryPaths {
26 var file *hcl.File
27 var fileDiags hcl.Diagnostics
28
29 b, err := fs.ReadFile(filename)
30 if err != nil {
31 diags = append(diags, &hcl.Diagnostic{
32 Severity: hcl.DiagError,
33 Summary: "Failed to read file",
34 Detail: fmt.Sprintf("The configuration file %q could not be read.", filename),
35 })
36 continue
37 }
38 if strings.HasSuffix(filename, ".json") {
39 file, fileDiags = parser.ParseJSON(b, filename)
40 } else {
41 file, fileDiags = parser.ParseHCL(b, filename)
42 }
43 diags = append(diags, fileDiags...)
44 if file == nil {
45 continue
46 }
47
48 contentDiags := LoadModuleFromFile(file, mod)
49 diags = append(diags, contentDiags...)
50 }
51
52 return mod, diagnosticsHCL(diags)
53 }
54
55 // LoadModuleFromFile reads given file, interprets it and stores in given Module
56 // This is useful for any caller which does tokenization/parsing on its own
57 // e.g. because it will reuse these parsed files later for more detailed
58 // interpretation.
59 func LoadModuleFromFile(file *hcl.File, mod *Module) hcl.Diagnostics {
60 var diags hcl.Diagnostics
61 content, _, contentDiags := file.Body.PartialContent(rootSchema)
62 diags = append(diags, contentDiags...)
63
64 for _, block := range content.Blocks {
65 switch block.Type {
66
67 case "terraform":
68 content, _, contentDiags := block.Body.PartialContent(terraformBlockSchema)
69 diags = append(diags, contentDiags...)
70
71 if attr, defined := content.Attributes["required_version"]; defined {
72 var version string
73 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version)
74 diags = append(diags, valDiags...)
75 if !valDiags.HasErrors() {
76 mod.RequiredCore = append(mod.RequiredCore, version)
77 }
78 }
79
80 for _, innerBlock := range content.Blocks {
81 switch innerBlock.Type {
82 case "required_providers":
83 reqs, reqsDiags := decodeRequiredProvidersBlock(innerBlock)
84 diags = append(diags, reqsDiags...)
85 for name, req := range reqs {
86 if _, exists := mod.RequiredProviders[name]; !exists {
87 mod.RequiredProviders[name] = req
88 } else {
89 if req.Source != "" {
90 source := mod.RequiredProviders[name].Source
91 if source != "" && source != req.Source {
92 diags = append(diags, &hcl.Diagnostic{
93 Severity: hcl.DiagError,
94 Summary: "Multiple provider source attributes",
95 Detail: fmt.Sprintf("Found multiple source attributes for provider %s: %q, %q", name, source, req.Source),
96 Subject: &innerBlock.DefRange,
97 })
98 } else {
99 mod.RequiredProviders[name].Source = req.Source
100 }
101 }
102
103 mod.RequiredProviders[name].VersionConstraints = append(mod.RequiredProviders[name].VersionConstraints, req.VersionConstraints...)
104 }
105 }
106 }
107 }
108
109 case "variable":
110 content, _, contentDiags := block.Body.PartialContent(variableSchema)
111 diags = append(diags, contentDiags...)
112
113 name := block.Labels[0]
114 v := &Variable{
115 Name: name,
116 Pos: sourcePosHCL(block.DefRange),
117 }
118
119 mod.Variables[name] = v
120
121 if attr, defined := content.Attributes["type"]; defined {
122 // We handle this particular attribute in a somewhat-tricky way:
123 // since Terraform may evolve its type expression syntax in
124 // future versions, we don't want to be overly-strict in how
125 // we handle it here, and so we'll instead just take the raw
126 // source provided by the user, using the source location
127 // information in the expression object.
128 //
129 // However, older versions of Terraform expected the type
130 // to be a string containing a keyword, so we'll need to
131 // handle that as a special case first for backward compatibility.
132
133 var typeExpr string
134
135 var typeExprAsStr string
136 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &typeExprAsStr)
137 if !valDiags.HasErrors() {
138 typeExpr = typeExprAsStr
139 } else {
140 rng := attr.Expr.Range()
141 typeExpr = string(rng.SliceBytes(file.Bytes))
142 }
143
144 v.Type = typeExpr
145 }
146
147 if attr, defined := content.Attributes["description"]; defined {
148 var description string
149 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &description)
150 diags = append(diags, valDiags...)
151 v.Description = description
152 }
153
154 if attr, defined := content.Attributes["default"]; defined {
155 // To avoid the caller needing to deal with cty here, we'll
156 // use its JSON encoding to convert into an
157 // approximately-equivalent plain Go interface{} value
158 // to return.
159 val, valDiags := attr.Expr.Value(nil)
160 diags = append(diags, valDiags...)
161 if val.IsWhollyKnown() { // should only be false if there are errors in the input
162 valJSON, err := ctyjson.Marshal(val, val.Type())
163 if err != nil {
164 // Should never happen, since all possible known
165 // values have a JSON mapping.
166 panic(fmt.Errorf("failed to serialize default value as JSON: %s", err))
167 }
168 var def interface{}
169 err = json.Unmarshal(valJSON, &def)
170 if err != nil {
171 // Again should never happen, because valJSON is
172 // guaranteed valid by ctyjson.Marshal.
173 panic(fmt.Errorf("failed to re-parse default value from JSON: %s", err))
174 }
175 v.Default = def
176 }
177 } else {
178 v.Required = true
179 }
180
181 if attr, defined := content.Attributes["sensitive"]; defined {
182 var sensitive bool
183 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &sensitive)
184 diags = append(diags, valDiags...)
185 v.Sensitive = sensitive
186 }
187
188 case "output":
189
190 content, _, contentDiags := block.Body.PartialContent(outputSchema)
191 diags = append(diags, contentDiags...)
192
193 name := block.Labels[0]
194 o := &Output{
195 Name: name,
196 Pos: sourcePosHCL(block.DefRange),
197 }
198
199 mod.Outputs[name] = o
200
201 if attr, defined := content.Attributes["description"]; defined {
202 var description string
203 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &description)
204 diags = append(diags, valDiags...)
205 o.Description = description
206 }
207
208 if attr, defined := content.Attributes["sensitive"]; defined {
209 var sensitive bool
210 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &sensitive)
211 diags = append(diags, valDiags...)
212 o.Sensitive = sensitive
213 }
214
215 case "provider":
216
217 content, _, contentDiags := block.Body.PartialContent(providerConfigSchema)
218 diags = append(diags, contentDiags...)
219
220 name := block.Labels[0]
221 // Even if there isn't an explicit version required, we still
222 // need an entry in our map to signal the unversioned dependency.
223 if _, exists := mod.RequiredProviders[name]; !exists {
224 mod.RequiredProviders[name] = &ProviderRequirement{}
225 }
226 if attr, defined := content.Attributes["version"]; defined {
227 var version string
228 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version)
229 diags = append(diags, valDiags...)
230 if !valDiags.HasErrors() {
231 mod.RequiredProviders[name].VersionConstraints = append(mod.RequiredProviders[name].VersionConstraints, version)
232 }
233 }
234
235 providerKey := name
236 var alias string
237 if attr, defined := content.Attributes["alias"]; defined {
238 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &alias)
239 diags = append(diags, valDiags...)
240 if !valDiags.HasErrors() && alias != "" {
241 providerKey = fmt.Sprintf("%s.%s", name, alias)
242 }
243 }
244
245 mod.ProviderConfigs[providerKey] = &ProviderConfig{
246 Name: name,
247 Alias: alias,
248 }
249
250 case "resource", "data":
251
252 content, _, contentDiags := block.Body.PartialContent(resourceSchema)
253 diags = append(diags, contentDiags...)
254
255 typeName := block.Labels[0]
256 name := block.Labels[1]
257
258 r := &Resource{
259 Type: typeName,
260 Name: name,
261 Pos: sourcePosHCL(block.DefRange),
262 }
263
264 var resourcesMap map[string]*Resource
265
266 switch block.Type {
267 case "resource":
268 r.Mode = ManagedResourceMode
269 resourcesMap = mod.ManagedResources
270 case "data":
271 r.Mode = DataResourceMode
272 resourcesMap = mod.DataResources
273 }
274
275 key := r.MapKey()
276
277 resourcesMap[key] = r
278
279 if attr, defined := content.Attributes["provider"]; defined {
280 // New style here is to provide this as a naked traversal
281 // expression, but we also support quoted references for
282 // older configurations that predated this convention.
283 traversal, travDiags := hcl.AbsTraversalForExpr(attr.Expr)
284 if travDiags.HasErrors() {
285 traversal = nil // in case we got any partial results
286
287 // Fall back on trying to parse as a string
288 var travStr string
289 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &travStr)
290 if !valDiags.HasErrors() {
291 var strDiags hcl.Diagnostics
292 traversal, strDiags = hclsyntax.ParseTraversalAbs([]byte(travStr), "", hcl.Pos{})
293 if strDiags.HasErrors() {
294 traversal = nil
295 }
296 }
297 }
298
299 // If we get out here with a nil traversal then we didn't
300 // succeed in processing the input.
301 if len(traversal) > 0 {
302 providerName := traversal.RootName()
303 alias := ""
304 if len(traversal) > 1 {
305 if getAttr, ok := traversal[1].(hcl.TraverseAttr); ok {
306 alias = getAttr.Name
307 }
308 }
309 r.Provider = ProviderRef{
310 Name: providerName,
311 Alias: alias,
312 }
313 } else {
314 diags = append(diags, &hcl.Diagnostic{
315 Severity: hcl.DiagError,
316 Summary: "Invalid provider reference",
317 Detail: "Provider argument requires a provider name followed by an optional alias, like \"aws.foo\".",
318 Subject: attr.Expr.Range().Ptr(),
319 })
320 }
321 } else {
322 // If provider _isn't_ set then we'll infer it from the
323 // resource type.
324 r.Provider = ProviderRef{
325 Name: resourceTypeDefaultProviderName(r.Type),
326 }
327 }
328
329 case "module":
330
331 content, _, contentDiags := block.Body.PartialContent(moduleCallSchema)
332 diags = append(diags, contentDiags...)
333
334 name := block.Labels[0]
335 mc := &ModuleCall{
336 Name: block.Labels[0],
337 Pos: sourcePosHCL(block.DefRange),
338 }
339
340 // check if this is overriding an existing module
341 var origSource string
342 if origMod, exists := mod.ModuleCalls[name]; exists {
343 origSource = origMod.Source
344 }
345
346 mod.ModuleCalls[name] = mc
347
348 if attr, defined := content.Attributes["source"]; defined {
349 var source string
350 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &source)
351 diags = append(diags, valDiags...)
352 mc.Source = source
353 }
354
355 if mc.Source == "" {
356 mc.Source = origSource
357 }
358
359 if attr, defined := content.Attributes["version"]; defined {
360 var version string
361 valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version)
362 diags = append(diags, valDiags...)
363 mc.Version = version
364 }
365
366 default:
367 // Should never happen because our cases above should be
368 // exhaustive for our schema.
369 panic(fmt.Errorf("unhandled block type %q", block.Type))
370 }
371 }
372
373 return diags
374 }