-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmoduletree.go
356 lines (312 loc) · 10.1 KB
/
moduletree.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
346
347
348
349
350
351
352
353
354
355
356
// © 2022-2023 Snyk Limited All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This module contains utilities for parsing and traversing everything in a
// configuration tree.
package hcl_interpreter
import (
"fmt"
"path/filepath"
"strings"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/spf13/afero"
"github.com/zclconf/go-cty/cty"
"github.com/snyk/policy-engine/pkg/internal/terraform/configs"
)
type ModuleMeta struct {
Dir string
Name ModuleName
Recurse bool
Filepaths []string
MissingRemoteModules []string
Location *hcl.Range
}
type ResourceMeta struct {
Data bool
Type string
ProviderType string
ProviderName string
ProviderVersionConstraint string
Multiple bool
Location hcl.Range
Body hcl.Body // For source code locations only.
}
// We load the entire tree of submodules in one pass.
type ModuleTree struct {
fs afero.Fs
meta *ModuleMeta
config hcl.Body // Call to the module, nil if root.
module *configs.Module
variableValues map[string]cty.Value // Variables set
children map[string]*ModuleTree
errors []error // Non-fatal errors encountered during loading
}
func ParseDirectory(
moduleRegister *TerraformModuleRegister,
parserFs afero.Fs,
dir string,
moduleName ModuleName,
varFiles []string,
) (*ModuleTree, error) {
parser := configs.NewParser(parserFs)
var diags hcl.Diagnostics
primary, _, diags := parser.ConfigDirFiles(dir)
if diags.HasErrors() {
return nil, diags
}
// ConfigDirFiles will return `main.tf` rather than `foo/bar/../../main.tf`.
// Rejoin the files using `TfFilePathJoin` to fix this.
filepaths := make([]string, len(primary))
for i, file := range primary {
filepaths[i] = TfFilePathJoin(dir, filepath.Base(file))
}
foundVarFiles, err := findVarFiles(parserFs, dir)
if err != nil {
return nil, err
}
// The order here is important so that var files that are explicitly specified get
// applied after any automatically-loaded var files.
varFiles = append(foundVarFiles, varFiles...)
return ParseFiles(moduleRegister, parserFs, true, dir, moduleName, filepaths, varFiles)
}
func ParseFiles(
moduleRegister *TerraformModuleRegister,
parserFs afero.Fs,
recurse bool,
dir string,
moduleName ModuleName,
filepaths []string,
varfiles []string,
) (*ModuleTree, error) {
meta := &ModuleMeta{
Dir: dir,
Name: moduleName,
Recurse: recurse,
Filepaths: filepaths,
}
parser := configs.NewParser(parserFs)
var diags hcl.Diagnostics
parsedFiles := make([]*configs.File, 0)
overrideFiles := make([]*configs.File, 0)
for _, file := range filepaths {
f, fDiags := parser.LoadConfigFile(file)
diags = append(diags, fDiags...)
parsedFiles = append(parsedFiles, f)
}
module, lDiags := configs.NewModule(parsedFiles, overrideFiles)
diags = append(diags, lDiags...)
// Deal with varfiles
variableValues := map[string]cty.Value{}
for _, varfile := range varfiles {
values, lDiags := parser.LoadValuesFile(varfile)
for k, v := range values {
variableValues[k] = v
}
diags = append(diags, lDiags...)
}
errors := []error{}
if diags.HasErrors() {
return nil, &multierror.Error{Errors: diags.Errs()}
}
if module == nil {
// Only actually throw an error if we don't have a module. We can
// still try and validate what we can.
return nil, fmt.Errorf(diags.Error())
}
children := map[string]*ModuleTree{}
if recurse {
for key, moduleCall := range module.ModuleCalls {
if body, ok := moduleCall.Config.(*hclsyntax.Body); ok {
if attr, ok := body.Attributes["source"]; ok {
if val, err := attr.Expr.Value(nil); err == nil && val.Type() == cty.String {
source := val.AsString()
childDir := TfFilePathJoin(dir, source)
childModuleName := ChildModuleName(moduleName, key)
if register := moduleRegister.GetDir(childModuleName); register != nil {
childDir = *register
} else if !moduleIsLocal(source) {
meta.MissingRemoteModules = append(
meta.MissingRemoteModules,
source,
)
continue
}
child, err := ParseDirectory(moduleRegister, parserFs, childDir, childModuleName, []string{})
if err == nil {
child.meta.Location = &moduleCall.SourceAddrRange
child.config = moduleCall.Config
children[key] = child
} else {
errors = append(
errors,
SubmoduleLoadingError{key, err},
)
}
}
}
}
}
}
return &ModuleTree{parserFs, meta, nil, module, variableValues, children, errors}, nil
}
func (mtree *ModuleTree) Errors() []error {
errors := make([]error, len(mtree.errors))
copy(errors, mtree.errors)
missingModules := mtree.meta.MissingRemoteModules
if len(missingModules) > 0 {
errors = append(errors, MissingRemoteSubmodulesError{mtree.meta.Dir, missingModules})
}
for _, child := range mtree.children {
errors = append(errors, child.Errors()...)
}
return errors
}
func (mtree *ModuleTree) FilePath() string {
if mtree.meta.Recurse {
return mtree.meta.Dir
} else {
return mtree.meta.Filepaths[0]
}
}
func (mtree *ModuleTree) LoadedFiles() []string {
filepaths := []string{filepath.Join(mtree.meta.Dir, ".terraform")}
if mtree.meta.Recurse {
filepaths = append(filepaths, mtree.meta.Dir)
}
for _, fp := range mtree.meta.Filepaths {
filepaths = append(filepaths, fp)
}
for _, child := range mtree.children {
if child != nil {
filepaths = append(filepaths, child.LoadedFiles()...)
}
}
return filepaths
}
type Visitor interface {
VisitModule(meta *ModuleMeta)
VisitResource(name FullName, resource *ResourceMeta)
VisitTerm(name FullName, term Term)
}
func (mtree *ModuleTree) Walk(v Visitor) {
walkModuleTree(v, mtree)
}
func walkModuleTree(v Visitor, mtree *ModuleTree) {
v.VisitModule(mtree.meta)
walkModule(v, mtree.meta.Name, mtree.module, mtree.variableValues)
for key, child := range mtree.children {
// TODO: This is not good. We end up walking child2 as it were child2.
configName := FullName{mtree.meta.Name, LocalName{"input", key}}
for k, input := range TermFromBody(child.config).Attributes() {
v.VisitTerm(configName.Add(k), input)
}
walkModuleTree(v, child)
}
}
func walkModule(v Visitor, moduleName ModuleName, module *configs.Module, variableValues map[string]cty.Value) {
name := EmptyFullName(moduleName)
for _, variable := range module.Variables {
if val, ok := variableValues[variable.Name]; ok {
expr := hclsyntax.LiteralValueExpr{Val: val}
v.VisitTerm(name.Add("variable").Add(variable.Name), TermFromExpr(&expr))
} else if !variable.Default.IsNull() {
expr := hclsyntax.LiteralValueExpr{
Val: variable.Default,
SrcRange: variable.DeclRange,
}
v.VisitTerm(name.Add("variable").Add(variable.Name), TermFromExpr(&expr))
} else {
val := cty.NullVal(variable.Type)
if variable.Type == cty.String {
// If no default is provided, we can add our own default depending
// on the type. We currently only do this for strings.
selfRef := name.Add("var").Add(variable.Name).ToString()
val = cty.StringVal(selfRef)
}
expr := hclsyntax.LiteralValueExpr{
Val: val,
SrcRange: variable.DeclRange,
}
v.VisitTerm(name.Add("variable").Add(variable.Name), TermFromExpr(&expr))
}
}
for _, local := range module.Locals {
v.VisitTerm(name.Add("local").Add(local.Name), TermFromExpr(local.Expr))
}
for _, resource := range module.DataResources {
walkResource(v, moduleName, module, resource, true)
}
for _, resource := range module.ManagedResources {
walkResource(v, moduleName, module, resource, false)
}
for _, output := range module.Outputs {
if output.Expr != nil {
v.VisitTerm(name.Add("output").Add(output.Name), TermFromExpr(output.Expr))
}
}
for providerName, providerConf := range module.ProviderConfigs {
v.VisitTerm(ProviderConfigName(moduleName, providerName), TermFromBody(providerConf.Config))
}
}
func walkResource(
v Visitor,
moduleName ModuleName,
module *configs.Module,
resource *configs.Resource,
isDataResource bool,
) {
name := EmptyFullName(moduleName)
if isDataResource {
name = name.Add("data")
}
name = name.Add(resource.Type).Add(resource.Name)
haveCount := resource.Count != nil
haveForEach := resource.ForEach != nil
providerName := resource.ProviderConfigAddr().StringCompact()
resourceMeta := &ResourceMeta{
Data: isDataResource,
ProviderName: providerName,
ProviderType: resource.Provider.Type,
Type: resource.Type,
Location: resource.DeclRange,
Multiple: haveCount || haveForEach,
Body: resource.Config,
}
if providerReqs, ok := module.ProviderRequirements.RequiredProviders[resource.ProviderConfigAddr().LocalName]; ok {
resourceMeta.ProviderVersionConstraint = providerReqs.Requirement.Required.String()
}
v.VisitResource(name, resourceMeta)
term := TermFromBody(resource.Config)
v.VisitTerm(name, term)
}
// TfFilePathJoin is like `filepath.Join` but avoids cleaning the path. This
// allows to get unique paths for submodules including a parent module, e.g.:
//
// .
// examples/mssql/../../
// examples/complete/../../
func TfFilePathJoin(leading, trailing string) string {
if filepath.IsAbs(trailing) {
return trailing
} else if leading == "." {
return trailing
} else {
trailing = filepath.FromSlash(trailing)
sep := string(filepath.Separator)
trailing = strings.TrimPrefix(trailing, "."+sep)
return strings.TrimRight(leading, sep) + sep +
strings.TrimLeft(trailing, sep)
}
}