/
parser.go
1617 lines (1335 loc) · 43.8 KB
/
parser.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package hclconfig
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/jumppad-labs/hclconfig/errors"
"github.com/jumppad-labs/hclconfig/registry"
"github.com/jumppad-labs/hclconfig/resources"
"github.com/jumppad-labs/hclconfig/types"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var rootContext *hcl.EvalContext
type ResourceTypeNotExistError struct {
Type string
File string
}
func (r ResourceTypeNotExistError) Error() string {
return fmt.Sprintf("Resource type %s defined in file %s, is not a registered resource.", r.Type, r.File)
}
type ParserOptions struct {
// list of default variable values to add to the parser
Variables map[string]string
// list of variable files to be read by the parser
VariablesFiles []string
// environment variable prefix
VariableEnvPrefix string
// location of any downloaded modules
ModuleCache string
// default registry to use when fetching modules
DefaultRegistry string
// credentials to use with the registries
RegistryCredentials map[string]string
// Callback executed when the parser reads a resource stanza, callbacks are
// executed based on a directed acyclic graph. If resource 'a' references
// a property defined in resource 'b', i.e 'resource.a.myproperty' then the
// callback for resource 'b' will be executed before resource 'a'. This allows
// you to set the dependent properties of resource 'b' before resource 'a'
// consumes them.
Callback WalkCallback
// PrimativesOnly will parse a structure including modules:
// * registered types for the resources are not loaded, all resources are
// parsed as ResourceBase, custom properties are discarded
// * the graph of resources is not walked, any interpolated properties
// are not resolved.
PrimativesOnly bool
}
// DefaultOptions returns a ParserOptions object with the
// ModuleCache set to the default directory of $HOME/.hclconfig/cache
// if the $HOME folder can not be determined, the cache is set to the
// current folder
// VariableEnvPrefix is set to 'HCL_VAR_', should a variable be defined
// called 'foo' setting the environment variable 'HCL_VAR_foo' will override
// any default value
func DefaultOptions() *ParserOptions {
cacheDir, err := os.UserHomeDir()
if err != nil {
cacheDir = "."
}
cacheDir = filepath.Join(cacheDir, ".hclconfig", "cache")
os.MkdirAll(cacheDir, os.ModePerm)
registryCredentials := map[string]string{}
return &ParserOptions{
ModuleCache: cacheDir,
VariableEnvPrefix: "HCL_VAR_",
RegistryCredentials: registryCredentials,
}
}
// Parser can parse HCL configuration files
type Parser struct {
options ParserOptions
registeredTypes types.RegisteredTypes
registeredFunctions map[string]function.Function
}
// NewParser creates a new parser with the given options
// if options are nil, default options are used
func NewParser(options *ParserOptions) *Parser {
o := options
if o == nil {
o = DefaultOptions()
}
return &Parser{options: *o, registeredTypes: resources.DefaultResources(), registeredFunctions: map[string]function.Function{}}
}
// RegisterType type registers a struct that implements Resource with the given name
// the parser uses this list to convert hcl defined resources into concrete types
func (p *Parser) RegisterType(name string, resource types.Resource) {
p.registeredTypes[name] = resource
}
// RegisterFunction type registers a custom interpolation function
// with the given name
// the parser uses this list to convert hcl defined resources into concrete types
func (p *Parser) RegisterFunction(name string, f interface{}) error {
ctyFunc, err := createCtyFunctionFromGoFunc(f)
if err != nil {
return nil
}
p.registeredFunctions[name] = ctyFunc
return nil
}
// ParseDirectory parses all resources in the given file
// error can be cast to *ConfigError to get a list of errors
func (p *Parser) ParseFile(file string) (*Config, error) {
c := NewConfig()
rootContext = buildContext(file, p.registeredFunctions)
ce := errors.NewConfigError()
err := p.parseFile(rootContext, file, c, p.options.Variables, p.options.VariablesFiles)
if err != nil {
for _, e := range err {
ce.AppendError(e)
}
return nil, ce
}
for _, rt := range c.Resources {
// call the resources Parse function if set
// if the config implements the processable interface call the resource process method
if p, ok := rt.(types.Parsable); ok {
err := p.Parse(c)
if err != nil {
de := errors.ParserError{}
de.Line = rt.Metadata().Line
de.Column = rt.Metadata().Column
de.Filename = rt.Metadata().File
de.Message = fmt.Sprintf(`error parsing resource "%s" %s`, resources.FQRNFromResource(rt).String(), err)
ce.AppendError(de)
}
}
}
if len(ce.Errors) > 0 {
return nil, ce
}
// do not walk the dag when we are only dealing with primatives
if p.options.PrimativesOnly {
return c, nil
}
// process the files and resolve dependency
return c, p.process(c)
}
// ParseDirectory parses all resource and variable files in the given directory
// note: this method does not recurse into sub folders
// error can be cast to *ConfigError to get a list of errors
func (p *Parser) ParseDirectory(dir string) (*Config, error) {
c := NewConfig()
rootContext = buildContext(dir, p.registeredFunctions)
ce := errors.NewConfigError()
err := p.parseDirectory(rootContext, dir, c)
if err != nil {
for _, e := range err {
ce.AppendError(e)
}
return nil, ce
}
for _, rt := range c.Resources {
// call the resources Parse function if set
// if the config implements the processable interface call the resource process method
if p, ok := rt.(types.Parsable); ok {
err := p.Parse(c)
if err != nil {
de := errors.ParserError{}
de.Line = rt.Metadata().Line
de.Column = rt.Metadata().Column
de.Filename = rt.Metadata().File
de.Message = fmt.Sprintf(`error parsing resource "%s" %s`, resources.FQRNFromResource(rt).String(), err)
ce.AppendError(de)
}
}
}
if len(ce.Errors) > 0 {
return nil, ce
}
// do not walk the dag when we are only dealing with primatives
if p.options.PrimativesOnly {
return c, nil
}
// process the files and resolve dependency
return c, p.process(c)
}
// UnmarshalJSON parses a JSON string from a serialized Config and returns a
// valid Config.
func (p *Parser) UnmarshalJSON(d []byte) (*Config, error) {
conf := NewConfig()
var objMap map[string]*json.RawMessage
err := json.Unmarshal(d, &objMap)
if err != nil {
return nil, err
}
var rawMessagesForResources []*json.RawMessage
err = json.Unmarshal(*objMap["resources"], &rawMessagesForResources)
if err != nil {
return nil, err
}
for _, m := range rawMessagesForResources {
mm := map[string]interface{}{}
err := json.Unmarshal(*m, &mm)
if err != nil {
return nil, err
}
meta := mm["meta"].(map[string]interface{})
r, err := p.registeredTypes.CreateResource(meta["type"].(string), meta["name"].(string))
if err != nil {
return nil, err
}
resData, _ := json.Marshal(mm)
json.Unmarshal(resData, r)
conf.addResource(r, nil, nil)
}
return conf, nil
}
// internal method
func (p *Parser) parseDirectory(ctx *hcl.EvalContext, dir string, c *Config) []error {
// get all files in a directory
path, err := os.Stat(dir)
if os.IsNotExist(err) {
return []error{fmt.Errorf("directory %s does not exist", dir)}
}
if !path.IsDir() {
return []error{fmt.Errorf("%s is not a directory", dir)}
}
files, err := ioutil.ReadDir(dir)
if err != nil {
return []error{fmt.Errorf("unable to list files in directory %s, error: %s", dir, err)}
}
variablesFiles := p.options.VariablesFiles
// first process vars files
for _, f := range files {
fn := filepath.Join(dir, f.Name())
if !f.IsDir() {
if strings.HasSuffix(fn, ".vars") {
// add to the collection
variablesFiles = append(variablesFiles, fn)
}
}
}
for _, f := range files {
fn := filepath.Join(dir, f.Name())
if !f.IsDir() {
if strings.HasSuffix(fn, ".hcl") {
err := p.parseFile(ctx, fn, c, p.options.Variables, variablesFiles)
if err != nil {
return err
}
}
}
}
return nil
}
// parseFile loads variables and resources from the given file
func (p *Parser) parseFile(
ctx *hcl.EvalContext,
file string,
c *Config,
variables map[string]string,
variablesFile []string) []error {
// This must be done before any other process as the resources
// might reference the variables
err := p.parseVariablesInFile(ctx, file, c)
if err != nil {
return []error{err}
}
// override any variables from files
for _, vf := range variablesFile {
err := p.loadVariablesFromFile(ctx, vf)
if err != nil {
return []error{err}
}
}
// override default values for variables from environment or variables map
p.setVariables(ctx, variables)
errs := p.parseResourcesInFile(ctx, file, c, "", false, []string{})
if errs != nil {
return errs
}
return nil
}
// loadVariablesFromFile loads variable values from a file
func (p *Parser) loadVariablesFromFile(ctx *hcl.EvalContext, path string) error {
parser := hclparse.NewParser()
f, diag := parser.ParseHCLFile(path)
if diag.HasErrors() {
de := errors.ParserError{}
de.Line = diag[0].Subject.Start.Line
de.Column = diag[0].Subject.Start.Line
de.Filename = path
de.Message = fmt.Sprintf("unable to parse file: %s", diag[0].Detail)
}
attrs, _ := f.Body.JustAttributes()
for name, attr := range attrs {
val, _ := attr.Expr.Value(ctx)
setContextVariable(ctx, name, val)
}
return nil
}
// setVariables allow variables to be set from a collection or environment variables
// Precedence should be file, env, vars
func (p *Parser) setVariables(ctx *hcl.EvalContext, vars map[string]string) {
// first any vars defined as environment variables
for _, e := range os.Environ() {
if strings.HasPrefix(e, p.options.VariableEnvPrefix) {
parts := strings.Split(e, "=")
if len(parts) == 2 {
key := strings.Replace(parts[0], p.options.VariableEnvPrefix, "", -1)
setContextVariable(ctx, key, valueFromString(parts[1]))
}
}
}
// then set vars
for k, v := range vars {
setContextVariable(ctx, k, valueFromString(v))
}
}
func valueFromString(v string) cty.Value {
// attempt to parse the string value into a known type
if val, err := strconv.ParseInt(v, 10, 0); err == nil {
return cty.NumberIntVal(val)
}
if val, err := strconv.ParseBool(v); err == nil {
return cty.BoolVal(val)
}
// otherwise return a string
return cty.StringVal(v)
}
// ParseVariableFile parses a config file for variables
func (p *Parser) parseVariablesInFile(ctx *hcl.EvalContext, file string, c *Config) error {
parser := hclparse.NewParser()
f, diag := parser.ParseHCLFile(file)
if diag.HasErrors() {
de := errors.ParserError{}
if diag[0].Subject != nil {
de.Line = diag[0].Subject.Start.Line
de.Column = diag[0].Subject.Start.Line
}
de.Filename = file
de.Message = fmt.Sprintf("unable to parse file: %s", diag[0].Detail)
return &de
}
body, ok := f.Body.(*hclsyntax.Body)
if !ok {
panic("Error getting body")
}
for _, b := range body.Blocks {
switch b.Type {
case resources.TypeVariable:
r, _ := p.registeredTypes.CreateResource(resources.TypeVariable, b.Labels[0])
v := r.(*resources.Variable)
// add the checksum for the resource
cs, err := ReadFileLocation(b.Range().Filename, b.Range().Start.Line, b.TypeRange.Start.Column, b.Range().End.Line, b.Range().End.Column)
if err != nil {
panic(err)
}
r.Metadata().Checksum.Parsed = HashString(cs)
err = decodeBody(ctx, c, file, b, v, false)
if err != nil {
return err
}
// add the variable to the context
c.AppendResource(v)
val, _ := v.Default.(*hcl.Attribute).Expr.Value(ctx)
setContextVariableIfMissing(ctx, v.Meta.Name, val)
}
}
return nil
}
// parseResourcesInFile parses a hcl file and adds any found resources to the config
func (p *Parser) parseResourcesInFile(ctx *hcl.EvalContext, file string, c *Config, moduleName string, disabled bool, dependsOn []string) []error {
parser := hclparse.NewParser()
f, diag := parser.ParseHCLFile(file)
if diag.HasErrors() {
de := errors.ParserError{}
de.Line = diag[0].Subject.Start.Line
de.Column = diag[0].Subject.Start.Line
de.Filename = file
de.Message = fmt.Sprintf("unable to parse file: %s", diag[0].Detail)
return []error{&de}
}
body, ok := f.Body.(*hclsyntax.Body)
if !ok {
// this should never happen, body should always be a hclsyntax.Body
panic("Error getting body")
}
for _, b := range body.Blocks {
// check the resource has a name
if len(b.Labels) == 0 {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf("resource '%s' has no name, please specify resources using the syntax 'resource_type \"name\" {}'", b.Type)
return []error{&de}
}
// create the registered type if not a variable or output
// variables and outputs are processed in a separate run
switch b.Type {
case resources.TypeVariable:
continue
case resources.TypeModule:
err := p.parseModule(ctx, c, file, b, moduleName, dependsOn)
if err != nil {
return err
}
case resources.TypeOutput:
fallthrough
case resources.TypeLocal:
fallthrough
case types.TypeResource:
err := p.parseResource(ctx, c, file, b, moduleName, dependsOn, disabled)
if err != nil {
return []error{err}
}
default:
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf("unable to process stanza '%s' in file %s at %d,%d , only 'variable', 'resource', 'module', and 'output' are valid stanza blocks", b.Type, file, b.Range().Start.Line, b.Range().Start.Column)
return []error{&de}
}
}
return nil
}
func setDisabled(ctx *hcl.EvalContext, r types.Resource, b *hclsyntax.Body, parentDisabled bool) error {
if b == nil {
return nil
}
if parentDisabled {
r.SetDisabled(true)
return nil
}
if attr, ok := b.Attributes["disabled"]; ok {
disabled, diags := attr.Expr.Value(ctx)
if diags.HasErrors() {
return fmt.Errorf("unable to read source from module: %s", diags.Error())
}
r.SetDisabled(disabled.True())
}
return nil
}
func setDependsOn(ctx *hcl.EvalContext, r types.Resource, b *hclsyntax.Body, dependsOn []string) error {
for _, d := range dependsOn {
r.AddDependency(d)
}
if attr, ok := b.Attributes["depends_on"]; ok {
dependsOnVal, diags := attr.Expr.Value(ctx)
if diags.HasErrors() {
return fmt.Errorf("unable to read depends_on attribute: %s", diags.Error())
}
// depends on is a slice of string
dependsOnSlice := dependsOnVal.AsValueSlice()
for _, d := range dependsOnSlice {
_, err := resources.ParseFQRN(d.AsString())
if err != nil {
return fmt.Errorf("invalid dependency %s, %s", d.AsString(), err)
}
r.AddDependency(d.AsString())
}
}
return nil
}
func (p *Parser) parseModule(ctx *hcl.EvalContext, c *Config, file string, b *hclsyntax.Block, moduleName string, dependsOn []string) []error {
// check the module has a name
if len(b.Labels) != 1 {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Level = errors.ParserErrorLevelError
de.Message = `invalid syntax for 'module' stanza, modules should be formatted 'module "name" {}`
return []error{&de}
}
name := b.Labels[0]
if err := validateResourceName(name); err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Level = errors.ParserErrorLevelError
de.Message = err.Error()
return []error{&de}
}
rt, _ := resources.DefaultResources().CreateResource(string(resources.TypeModule), b.Labels[0])
rt.Metadata().Module = moduleName
rt.Metadata().File = file
rt.Metadata().Line = b.TypeRange.Start.Line
rt.Metadata().Column = b.TypeRange.Start.Column
err := decodeBody(ctx, c, file, b, rt, false)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Level = errors.ParserErrorLevelError
de.Message = fmt.Sprintf("error creating resource: %s", err)
return []error{&de}
}
setDisabled(ctx, rt, b.Body, false)
derr := setDependsOn(ctx, rt, b.Body, dependsOn)
if derr != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Level = errors.ParserErrorLevelError
de.Message = derr.Error()
return []error{&de}
}
// we need to fetch the source so that we can process the child resources
// "source" is the attribute but we need to read this manually
src, diags := b.Body.Attributes["source"].Expr.Value(ctx)
if diags.HasErrors() {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Level = errors.ParserErrorLevelError
de.Message = fmt.Sprintf("unable to read source from module: %s", diags.Error())
return []error{&de}
}
version := "latest"
if b.Body.Attributes["version"] != nil {
v, diags := b.Body.Attributes["version"].Expr.Value(ctx)
if diags.HasErrors() {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Level = errors.ParserErrorLevelError
de.Message = fmt.Sprintf("unable to read version from module: %s", diags.Error())
return []error{&de}
}
version = v.AsString()
}
rt.(*resources.Module).Source = src.AsString()
rt.(*resources.Module).Version = version
// src could be a registry url, github repository or a relative folder
// first check if it is a folder, we need to make it absolute relative to the current file
dir := path.Dir(file)
moduleSrc := path.Join(dir, src.AsString())
fi, serr := os.Stat(moduleSrc)
if serr != nil || !fi.IsDir() {
moduleURL := src.AsString()
parts := strings.Split(moduleURL, "/")
// if there are 2 parts (namespace, module), check if the default registry is set
if len(parts) == 2 && p.options.DefaultRegistry != "" {
parts = append([]string{p.options.DefaultRegistry}, parts...)
}
// if there are 3 parts (registry, namespace, module) it could be a registry
if len(parts) == 3 {
host := parts[0]
namespace := parts[1]
name := parts[2]
// check if the registry has credentials
var token string
if _, ok := p.options.RegistryCredentials[host]; ok {
token = p.options.RegistryCredentials[host]
}
// if we can't create a registry, it is not a module registry so we can ignore the error
r, err := registry.New(host, token)
if err == nil {
// get all available versions of the module from the registry
// check if the requested version exists
versions, err := r.GetModuleVersions(namespace, name)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = err.Error()
return []error{&de}
}
// if no version is set, use latest
if version == "latest" {
version = versions.Latest
} else {
// otherwise check the version exists
versionExists := false
for _, v := range versions.Versions {
if v.Version == version {
versionExists = true
break
}
}
if !versionExists {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf(`version "%s" does not exist for module "%s/%s" in registry "%s"`, version, namespace, name, host)
return []error{&de}
}
}
module, err := r.GetModule(namespace, name, version)
if err == nil {
// if we get back a module url from the registry,
// set the source to the returned url
moduleURL = module.DownloadURL
} else {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf(`unable to fetch module "%s/%s" from registry "%s": %s`, namespace, name, host, err)
return []error{&de}
}
}
}
// is not a directory fetch from source using go getter
gg := NewGoGetter()
mp, err := gg.Get(moduleURL, p.options.ModuleCache, false)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf(`unable to fetch remote module "%s": %s`, src.AsString(), err)
return []error{&de}
}
moduleSrc = mp
}
// create a new config and add the resources later
moduleConfig := NewConfig()
// modules should have their own context so that variables are not globally scoped
subContext := buildContext(moduleSrc, p.registeredFunctions)
errs := p.parseDirectory(subContext, moduleSrc, moduleConfig)
if errs != nil {
return errs
}
rt.(*resources.Module).SubContext = subContext
// add the module
c.addResource(rt, ctx, b.Body)
// we need to add the module name to all the returned resources
for _, r := range moduleConfig.Resources {
// ensure the module name has the parent appended to it
r.Metadata().Module = fmt.Sprintf("%s.%s", name, r.Metadata().Module)
r.Metadata().Module = strings.TrimSuffix(r.Metadata().Module, ".")
ctx, err := moduleConfig.getContext(r)
if err != nil {
panic("no body found for resource")
}
bdy, err := moduleConfig.getBody(r)
if err != nil {
panic("no body found for resource")
}
// set disabled
setDisabled(ctx, r, bdy, rt.GetDisabled())
// depends on is a property of the embedded type we need to set this manually
err = setDependsOn(ctx, rt, b.Body, dependsOn)
if err != nil {
return []error{err}
}
err = c.addResource(r, ctx, bdy)
if err != nil {
return []error{err}
}
}
return nil
}
func (p *Parser) parseResource(ctx *hcl.EvalContext, c *Config, file string, b *hclsyntax.Block, moduleName string, dependsOn []string, disabled bool) error {
var rt types.Resource
var err error
ignoreErrors := false
switch b.Type {
case types.TypeResource:
// if the type is resource there should be two labels, one for the type and one for the name
if len(b.Labels) != 2 {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = `"invalid formatting for 'resource' stanza, resources should have a name and a type, i.e. 'resource "type" "name" {}'`
return &de
}
name := b.Labels[1]
if err := validateResourceName(name); err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = de.Error()
return &de
}
// PrimativesOnly parse to ResourceBase
if p.options.PrimativesOnly {
rt = &types.ResourceBase{
Meta: types.Meta{
Name: name,
Type: b.Labels[0],
Properties: map[string]interface{}{},
},
}
// ignore any errors when parsing
ignoreErrors = true
} else {
rt, err = p.registeredTypes.CreateResource(b.Labels[0], name)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf("unable to create resource '%s' %s", b.Type, err)
return &de
}
}
case resources.TypeLocal:
// if the type is local check there is one label
if len(b.Labels) != 1 {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = `invalid formatting for 'local' stanza, resources should have a name and a type, i.e. 'local "name" {}'`
return &de
}
name := b.Labels[0]
if err := validateResourceName(name); err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = err.Error()
return &de
}
rt, err = p.registeredTypes.CreateResource(resources.TypeLocal, name)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf(`unable to create local, this error should never happen %s`, err)
return &de
}
case resources.TypeOutput:
// if the type is output check there is one label
if len(b.Labels) != 1 {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = `invalid formatting for 'output' stanza, resources should have a name and a type, i.e. 'output "name" {}'`
return &de
}
name := b.Labels[0]
if err := validateResourceName(name); err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = err.Error()
return &de
}
rt, err = p.registeredTypes.CreateResource(resources.TypeOutput, name)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf(`unable to create output, this error should never happen %s`, err)
return &de
}
}
rt.Metadata().Module = moduleName
rt.Metadata().File = file
rt.Metadata().Line = b.TypeRange.Start.Line
rt.Metadata().Column = b.TypeRange.Start.Column
err = decodeBody(ctx, c, file, b, rt, ignoreErrors)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf("error creating resource '%s' in file %s: %s", b.Labels[0], file, err)
return &de
}
// if we have an output, get the description
// this is only needed when parsing primatives as
// this value is normally set during walk
if rt.Metadata().Type == resources.TypeOutput && b.Body.Attributes["description"] != nil {
desc, diags := b.Body.Attributes["description"].Expr.Value(ctx)
if !diags.HasErrors() {
rt.(*resources.Output).Description = desc.AsString()
}
}
// disabled is a property of the embedded type we need to add this manually
setDisabled(ctx, rt, b.Body, disabled)
// depends on is a property of the embedded type we need to set this manually
err = setDependsOn(ctx, rt, b.Body, dependsOn)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf(`unable to set depends_on, %s`, err)
return &de
}
err = c.addResource(rt, ctx, b.Body)
if err != nil {
de := errors.ParserError{}
de.Line = b.TypeRange.Start.Line
de.Column = b.TypeRange.Start.Column
de.Filename = file
de.Message = fmt.Sprintf(`unable to add resource "%s" to config %s`, resources.FQRNFromResource(rt).String(), err)
return &de
}
return nil
}
func setContextVariableIfMissing(ctx *hcl.EvalContext, key string, value cty.Value) {
if m, ok := ctx.Variables["variable"]; ok {
if _, ok := m.AsValueMap()[key]; ok {
return
}
}