/
renderer.go
1358 lines (1240 loc) · 39.1 KB
/
renderer.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
// Copyright 2016-2021, Pulumi Corporation.
package cf2pulumi
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/goccy/go-yaml/ast"
"github.com/goccy/go-yaml/parser"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-aws-native/provider/pkg/metadata"
"github.com/pulumi/pulumi-aws-native/provider/pkg/naming"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
)
// null represents PCL's builtin `null` variable
var null = &model.Variable{
Name: "null",
VariableType: model.NoneType,
}
// pseudoParameters is the set of CFN pseudo-parameters.
var pseudoParameters = codegen.NewStringSet("AWS::NoValue",
"AWS::AccountId",
"AWS::Partition",
"AWS::Region",
"AWS::StackName",
"AWS::StackId",
"AWS::URLSuffix")
// functions is the set of CFN functions.
var functions = codegen.NewStringSet("Condition",
"Fn::And",
"Fn::Base64",
"Fn::Cidr",
"Fn::Equals",
"Fn::FindInMap",
"Fn::GetAtt",
"Fn::GetAZs",
"Fn::If",
"Fn::ImportValue",
"Fn::Join",
"Fn::Not",
"Fn::Or",
"Fn::Select",
"Fn::Split",
"Fn::Sub",
"Fn::Transform",
"Ref")
// functionTags maps from tags that represent the short forms of functions to their corresponding function names.
var functionTags = map[string]string{
"!Condition": "Condition",
"!And": "Fn::And",
"!Base64": "Fn::Base64",
"!Cidr": "Fn::Cidr",
"!Equals": "Fn::Equals",
"!FindInMap": "Fn::FindInMap",
"!GetAtt": "Fn::GetAtt",
"!GetAZs": "Fn::GetAZs",
"!If": "Fn::If",
"!ImportValue": "Fn::ImportValue",
"!Join": "Fn::Join",
"!Not": "Fn::Not",
"!Or": "Fn::Or",
"!Select": "Fn::Select",
"!Split": "Fn::Split",
"!Sub": "Fn::Sub",
"!Transform": "Fn::Transform",
"!Ref": "Ref",
}
// A renderContext contains the state necessary to render a CloudFormation template to a Pulumi program.
type renderContext struct {
// The maps below map from names in the CloudFormation template to output variables. These maps are used during
// rendering to emit appropriate references to the renamed entities. Entities need to be renamed because they
// are namespaced by type in CloudFormation, but the corresponding declarations are not namespaced in PCL.
pseudoParameters map[string]*model.Variable // AWS pseudo parameters
parameters map[string]*model.Variable // Template parameters
ssmParameters map[string]*model.Variable // SSM Template parameters
mappings map[string]*model.Variable // Template mappings
conditions map[string]*model.Variable // Template conditions
resources map[string]*model.Variable // Template resources
outputs map[string]*model.Variable // Template outputs
supportedResources codegen.StringSet // Tokens for supported resources
renderedPseudoParameters bool // True if pseudo parameters have been rendered
}
// checkArgsArray validates the argument to a CloudFormation function. If the argument is a sequence, its length is
// checked against the provided minimum and maximum arg count. If the sequence is valid, its values are returned.
//
// If the argument is a single value and the minimum count is greater than one, the argument is wrapped in an array
// and returned.
func (ctx *renderContext) checkArgsArray(name string, v ast.Node, min, max int) ([]ast.Node, error) {
if v.Type() != ast.SequenceType {
if min > 1 {
return nil, fmt.Errorf("the argument to '%s' must be an array", name)
}
return []ast.Node{v}, nil
}
arr := v.(*ast.SequenceNode).Values
if len(arr) < min || (max >= 0 && len(arr) > max) {
if min == max {
return nil, fmt.Errorf("the argument to '%s' must have exactly %v elements", name, min)
}
if max >= 0 {
return nil, fmt.Errorf("the argument to '%s' must have between %v and %v elements", name, min, max)
}
return nil, fmt.Errorf("the argument to '%s' must have at least %v elements", name, min)
}
return arr, nil
}
// renderRef renders a reference to a pseudo-parameter, parameter, or resource. These entities all correspond to
// top-level variables in the Pulumi program, so each reference is rendered as a scope traversal expression.
func (ctx *renderContext) renderRef(name string) (model.Expression, error) {
if pseudoParameters.Has(name) {
pseudoVar, ok := ctx.pseudoParameters[name]
if !ok {
return nil, fmt.Errorf("unknown pseudo parameter '%v'", name)
}
return model.VariableReference(pseudoVar), nil
}
v, ok := ctx.parameters[name]
if ok {
return model.VariableReference(v), nil
}
v, ok = ctx.resources[name]
if !ok {
return nil, fmt.Errorf("unknown parameter or resource '%v'", name)
}
return &model.ScopeTraversalExpression{
Traversal: hcl.Traversal{hcl.TraverseRoot{Name: v.Name}, hcl.TraverseAttr{Name: "id"}},
Parts: []model.Traversable{v, model.DynamicType},
}, nil
}
var holePattern = regexp.MustCompile(`\${([^}]*)}`)
// renderSub renders a call to Fn::Sub. The call is converted to a template expression. If an envrionment map is
// provided, references to map elements are replaced with the corresponding elements.
func (ctx *renderContext) renderSub(name string, value ast.Node) (model.Expression, error) {
arr, err := ctx.checkArgsArray(name, value, 1, 2)
if err != nil {
return nil, err
}
if arr[0].Type() != ast.StringType {
return nil, fmt.Errorf("the first argument to 'Fn::Sub' must be a string")
}
environment := make(map[string]model.Expression)
if len(arr) == 2 {
values, ok := mapValues(arr[1])
if !ok {
return nil, fmt.Errorf("the second argument to 'Fn::Sub' must be a mapping")
}
for _, f := range values {
v, err := ctx.renderValue(f.Value)
if err != nil {
return nil, err
}
environment[keyString(f)] = v
}
}
text := arr[0].(*ast.StringNode).Value
holes := holePattern.FindAllStringSubmatchIndex(text, -1)
var literals []string
var refs []model.Expression
start, end := 0, 0
for _, hole := range holes {
end = hole[0]
literals = append(literals, text[start:end])
ref := text[hole[2]:hole[3]]
switch {
case len(ref) == 0:
return nil, fmt.Errorf("empty variable in 'Fn::Sub' input string")
case ref[0] == '!':
literals[len(literals)-1] = literals[len(literals)-1] + ref
default:
x, err := ctx.renderRef(ref)
if err != nil {
v, ok := environment[ref]
if !ok {
return nil, err
}
x = v
}
refs = append(refs, x)
}
start = hole[1]
}
literals = append(literals, text[start:])
if len(literals) != len(refs)+1 {
return nil, fmt.Errorf("the number of literals must be exactly one more than the number of references in 'Fn::Sub'")
}
var parts []model.Expression
for i, l := range literals {
parts = append(parts, plainLit(l))
if i < len(refs) {
parts = append(parts, refs[i])
}
}
return &model.TemplateExpression{Parts: parts}, nil
}
// renderArgsArray validates and renders the argument to a function as an array of expressions.
func (ctx *renderContext) renderArgsArray(name string, arg ast.Node, min, max int) ([]model.Expression, error) {
arr, err := ctx.checkArgsArray(name, arg, min, max)
if err != nil {
return nil, err
}
var args []model.Expression
for _, v := range arr {
arg, err := ctx.renderValue(v)
if err != nil {
return nil, err
}
args = append(args, arg)
}
return args, nil
}
// renderJoin renders a call to Fn::Join. If the arguments to the join are a string literal and a sequence, the call
// is rendered as a template expression. Otherwise, it is rendered as a call to the `join` function.
func (ctx *renderContext) renderJoin(name string, arg ast.Node) (model.Expression, error) {
args, err := ctx.renderArgsArray(name, arg, 2, 2)
if err != nil {
return nil, err
}
call := &model.FunctionCallExpression{
Name: "join",
Args: args,
}
// Turn `join("lit", [ ... ])` into a template expression.
sep, ok := getStringValue(args[0])
if !ok {
return call, nil
}
tuple, ok := args[1].(*model.TupleConsExpression)
if !ok {
return call, nil
}
afterLiteral := false
var parts []model.Expression
for _, x := range tuple.Expressions {
lit, ok := getStringValue(x)
if ok {
if afterLiteral {
last := parts[len(parts)-1].(*model.LiteralValueExpression)
last.Value = cty.StringVal(last.Value.AsString() + sep + lit)
} else {
if len(parts) > 0 {
lit = sep + lit
}
parts = append(parts, plainLit(lit))
afterLiteral = true
}
} else {
if afterLiteral {
last := parts[len(parts)-1].(*model.LiteralValueExpression)
last.Value = cty.StringVal(last.Value.AsString() + sep + lit)
} else {
parts = append(parts, plainLit(sep))
}
parts = append(parts, x)
afterLiteral = false
}
}
if !afterLiteral {
parts = append(parts, plainLit(""))
}
return &model.TemplateExpression{Parts: parts}, nil
}
// renderFunctionCall renders a call to an AWS intrinsic function. The way the function is rendered depends on the
// function:
//
// - `Condition` is rendered as a reference to the equivalent condition variable
// - `Fn::And` is rendered as the logical and operator
// - `Fn::Base64` is rendered as a call to the `toBase64` function
// - `Fn::Cidr` is rendered as an invocation of `aws-native::cidr`
// - `Fn::Equals` is rendered as the equality operator
// - `Fn::FindInMap` is rendered as a two index expressions
// - `Fn::GetAtt` is rendered as a scope traversal expression on the referenced resource to fetch the referenced
// attribute
// - `Fn::GetAZs` is rendered as an invocation of `aws-native::getAzs`
// - `Fn::If` is rendered as the conditional operator
// - `Fn::ImportValue` is rendered as an invocation of `aws-native::importValue`
// - `Fn::Join` is rendered as either a template expression or a call to `join`
// - `Fn::Not` is rendered as the logical not operator
// - `Fn::Or` is rendered as the logical or operator
// - `Fn::Select` is rendered as an index expressions
// - `Fn::Split` is rendered as a call to `split`
// - `Fn::Sub` is rendered as a template expression
// - `Fn::Transform` is not supported
// - `Ref` is rendered as a variable reference
func (ctx *renderContext) renderFunctionCall(name string, arg ast.Node) (model.Expression, error) {
switch name {
case "Condition":
arg, err := ctx.renderValue(arg)
if err != nil {
return nil, err
}
condition, ok := getStringValue(arg)
if !ok {
return nil, fmt.Errorf("the argument to Condition must be a string")
}
condVar, ok := ctx.conditions[condition]
if !ok {
return nil, fmt.Errorf("unknown condition '%v'", condition)
}
return model.VariableReference(condVar), nil
case "Fn::And":
args, err := ctx.renderArgsArray(name, arg, 2, -1)
if err != nil {
return nil, err
}
leftOperand := args[0]
for _, arg := range args[1:] {
leftOperand = &model.BinaryOpExpression{
LeftOperand: leftOperand,
Operation: hclsyntax.OpLogicalAnd,
RightOperand: arg,
}
}
return leftOperand, nil
case "Fn::Base64":
arg, err := ctx.renderValue(arg)
if err != nil {
return nil, err
}
return &model.FunctionCallExpression{
Name: "toBase64",
Args: []model.Expression{
arg,
},
}, nil
case "Fn::Cidr":
args, err := ctx.renderArgsArray(name, arg, 3, 3)
if err != nil {
return nil, err
}
inputs := []model.ObjectConsItem{
objectConsItem("ipBlock", args[0]),
objectConsItem("count", args[1]),
objectConsItem("cidrBits", args[2]),
}
return relativeTraversal(invoke("aws-native::cidr", inputs...), "subnets"), nil
case "Fn::Equals":
args, err := ctx.renderArgsArray(name, arg, 2, 2)
if err != nil {
return nil, err
}
return &model.BinaryOpExpression{
LeftOperand: args[0],
Operation: hclsyntax.OpEqual,
RightOperand: args[1],
}, nil
case "Fn::FindInMap":
args, err := ctx.renderArgsArray(name, arg, 3, 3)
if err != nil {
return nil, err
}
mapName, ok := getStringValue(args[0])
if !ok {
return nil, fmt.Errorf("the first argument to 'Fn::FindInMap' must be a string")
}
mapVar, ok := ctx.mappings[mapName]
if !ok {
return nil, fmt.Errorf("unknown mapping '%v'", mapName)
}
return &model.IndexExpression{
Collection: &model.IndexExpression{
Collection: model.VariableReference(mapVar),
Key: args[1],
},
Key: args[2],
}, nil
case "Fn::GetAtt":
args, err := ctx.renderArgsArray(name, arg, 1, 2)
if err != nil {
return nil, err
}
var resourceName string
var attrArg model.Expression
if len(args) == 1 {
attrPath, ok := getStringValue(args[0])
if !ok {
return nil, fmt.Errorf("the argument to 'Fn::GetAtt' must be a string")
}
dotIndex := strings.Index(attrPath, ".")
if dotIndex == -1 {
return nil, fmt.Errorf("attribute paths must be of the form \"resourceName.attrName\"")
}
resourceName, attrArg = attrPath[:dotIndex], plainLit(attrPath[dotIndex+1:])
} else {
rn, ok := getStringValue(args[0])
if !ok {
return nil, fmt.Errorf("the first argument to 'Fn::GetAtt' must be a string")
}
resourceName, attrArg = rn, args[1]
}
resourceVar, ok := ctx.resources[resourceName]
if !ok {
return nil, fmt.Errorf("unknown resource '%v'", resourceName)
}
attrName, ok := getStringValue(attrArg)
if !ok {
return &model.IndexExpression{
Collection: &model.ScopeTraversalExpression{
Traversal: hcl.Traversal{
hcl.TraverseRoot{Name: resourceVar.Name},
},
Parts: []model.Traversable{
resourceVar,
model.DynamicType,
},
},
Key: args[1],
}, nil
}
sdkName := naming.ToSdkName(attrName)
return &model.ScopeTraversalExpression{
Traversal: hcl.Traversal{
hcl.TraverseRoot{Name: resourceVar.Name},
hcl.TraverseAttr{Name: strings.Replace(sdkName, ".", "", -1)},
},
Parts: []model.Traversable{
resourceVar,
model.DynamicType,
model.DynamicType,
},
}, nil
case "Fn::GetAZs":
region, err := ctx.renderValue(arg)
if err != nil {
return nil, err
}
return relativeTraversal(invoke("aws-native::getAzs", objectConsItem("region", region)), "azs"), nil
case "Fn::If":
args, err := ctx.renderArgsArray(name, arg, 3, 3)
if err != nil {
return nil, err
}
condition, ok := getStringValue(args[0])
if !ok {
return nil, fmt.Errorf("the first argument to 'Fn::If' must be a string")
}
condVar, ok := ctx.conditions[condition]
if !ok {
return nil, fmt.Errorf("unknown condition '%v'", condition)
}
return &model.ConditionalExpression{
Condition: model.VariableReference(condVar),
TrueResult: args[1],
FalseResult: args[2],
}, nil
case "Fn::ImportValue":
arg, err := ctx.renderValue(arg)
if err != nil {
return nil, err
}
return relativeTraversal(invoke("aws-native::importValue", objectConsItem("name", arg)), "value"), nil
case "Fn::Join":
return ctx.renderJoin(name, arg)
case "Fn::Not":
args, err := ctx.renderArgsArray(name, arg, 1, 1)
if err != nil {
return nil, err
}
return &model.UnaryOpExpression{
Operation: hclsyntax.OpLogicalNot,
Operand: args[0],
}, nil
case "Fn::Or":
args, err := ctx.renderArgsArray(name, arg, 2, -1)
if err != nil {
return nil, err
}
leftOperand := args[0]
for _, arg := range args[1:] {
leftOperand = &model.BinaryOpExpression{
LeftOperand: leftOperand,
Operation: hclsyntax.OpLogicalOr,
RightOperand: arg,
}
}
return leftOperand, nil
case "Fn::Select":
args, err := ctx.renderArgsArray(name, arg, 2, 2)
if err != nil {
return nil, err
}
indexStr, ok := getStringValue(args[0])
if ok {
indexInt, err := convert.Convert(cty.StringVal(indexStr), cty.Number)
if err == nil {
args[0] = &model.LiteralValueExpression{
Value: indexInt,
}
} else {
args[0] = quotedLit(indexStr)
}
}
return &model.IndexExpression{
Collection: args[1],
Key: args[0],
}, nil
case "Fn::Split":
args, err := ctx.renderArgsArray(name, arg, 2, 2)
if err != nil {
return nil, err
}
return &model.FunctionCallExpression{
Name: "split",
Args: args,
}, nil
case "Fn::Sub":
return ctx.renderSub(name, arg)
case "Fn::Transform":
return nil, fmt.Errorf("NYI: Fn::Transform")
case "Ref":
arg, err := ctx.renderValue(arg)
if err != nil {
return nil, err
}
entityName, ok := getStringValue(arg)
if !ok {
return nil, fmt.Errorf("the argument to 'Ref' must be a string")
}
return ctx.renderRef(entityName)
default:
contract.Failf("unexpected function %v", name)
return nil, nil
}
}
// renderValue renders an AST node that represents a YAML value as its equivalent PCL. Most nodes are rendered as one
// would expect (e.g. sequences -> tuple construction, maps -> object construction, etc.). Function calls are the lone
// exception; see renderFunction for more details.
func (ctx *renderContext) renderValue(node ast.Node) (model.Expression, error) {
switch node := node.(type) {
case *ast.SequenceNode:
var expressions []model.Expression
for _, v := range node.Values {
e, err := ctx.renderValue(v)
if err != nil {
return nil, err
}
expressions = append(expressions, e)
}
return &model.TupleConsExpression{
Expressions: expressions,
}, nil
case *ast.BoolNode:
return &model.LiteralValueExpression{
Value: cty.BoolVal(node.Value),
}, nil
case *ast.NullNode:
return model.VariableReference(null), nil
case *ast.FloatNode:
return &model.LiteralValueExpression{
Value: cty.NumberFloatVal(node.Value),
}, nil
case *ast.IntegerNode:
var value cty.Value
switch v := node.Value.(type) {
case int64:
value = cty.NumberIntVal(v)
case uint64:
value = cty.NumberUIntVal(v)
default:
contract.Failf("unexpected value of type %T in integer node", v)
}
return &model.LiteralValueExpression{Value: value}, nil
case *ast.LiteralNode:
return ctx.renderValue(node.Value)
case *ast.MappingKeyNode:
return ctx.renderValue(node.Value)
case *ast.MappingNode, *ast.MappingValueNode:
values, ok := mapValues(node)
if !ok {
return nil, fmt.Errorf("mapping must be a mapping of key-value pairs")
}
if len(values) == 1 && functions.Has(keyString(values[0])) {
return ctx.renderFunctionCall(keyString(values[0]), values[0].Value)
}
var items []model.ObjectConsItem
for _, f := range values {
v, err := ctx.renderValue(f.Value)
if err != nil {
return nil, err
}
items = append(items, objectConsItem(camel(keyString(f)), v))
}
return &model.ObjectConsExpression{
Items: items,
}, nil
case *ast.StringNode:
return quotedLit(node.Value), nil
case *ast.TagNode:
fnName, ok := functionTags[node.Start.Value]
if !ok {
return nil, fmt.Errorf("unknown tag %v", node.Start.Value)
}
return ctx.renderFunctionCall(fnName, node.Value)
default:
contract.Failf("unexpected YAML node of type %T", node)
return nil, nil
}
}
// renderPseudoParameter renders a reference to a pseudo parameter as an invocation of the corresponding getter in the
// cloudformation provider (or a reference to `null` for `AWS::NoValue`).
func renderPseudoParameter(name string) model.Expression {
getter := func(name string) model.Expression {
return relativeTraversal(invoke("aws-native::get"+name), camel(name))
}
switch name {
case "AWS::NoValue":
return model.VariableReference(null)
case "AWS::AccountId", "AWS::Partition", "AWS::Region", "AWS::StackName", "AWS::StackId":
return getter(name[strings.Index(name, "::")+2:])
case "AWS::URLSuffix":
return getter("UrlSuffix")
default:
contract.Failf("unexpected pseudo parameter '%v'", name)
return nil
}
}
// renderPseudoParameters renders all referenced pseudo parameters into PCL local variables whose values are
// invocations of the corresponding provider functions.
func (ctx *renderContext) renderPseudoParameters(items *[]model.BodyItem) {
if !ctx.renderedPseudoParameters {
for _, v := range pseudoParameters.SortedValues() {
if pseudoVar, ok := ctx.pseudoParameters[v]; ok {
*items = append(*items, &model.Attribute{
Name: pseudoVar.Name,
Value: renderPseudoParameter(v),
})
}
}
ctx.renderedPseudoParameters = true
}
}
// renderParameterType converts a CloudFormation parameter type to its equivalent PCL type.
func renderParameterType(s string) (string, bool) {
switch s {
case "String":
return "string", true
case "Number":
return "number", true
case "List<Number>":
return "list(number)", true
case "CommaDelimitedList", "List<String>":
return "list(string)", true
case "AWS::EC2::AvailabilityZone::Name",
"AWS::EC2::Image::Id",
"AWS::EC2::Instance::Id",
"AWS::EC2::KeyPair::KeyName",
"AWS::EC2::SecurityGroup::GroupName",
"AWS::EC2::SecurityGroup::Id",
"AWS::EC2::Subnet::Id",
"AWS::EC2::Volume::Id",
"AWS::EC2::VPC::Id",
"AWS::Route53::HostedZone::Id",
"AWS::SSM::Parameter::Name":
return "string", true
case "List<AWS::EC2::AvailabilityZone::Name>",
"List<AWS::EC2::Image::Id>",
"List<AWS::EC2::Instance::Id>",
"List<AWS::EC2::SecurityGroup::GroupName>",
"List<AWS::EC2::SecurityGroup::Id>",
"List<AWS::EC2::Subnet::Id>",
"List<AWS::EC2::Volume::Id>",
"List<AWS::EC2::VPC::Id>",
"List<AWS::Route53::HostedZone::Id>":
return "list(string)", true
default:
return "", false
}
}
var ssmPattern = regexp.MustCompile("AWS::SSM::Parameter::Value<(.*)>")
// renderParameter renders a template parameter. The parameter is rendered as either a sinmple config variable
// definition or a config variable definition and an invocation of one of the two SSM parameter getters (in the case of
// SSM parameters). Uses of SSM parameters reference the result of the invocation.
func (ctx *renderContext) renderParameter(attr *ast.MappingValueNode) ([]model.BodyItem, error) {
name := keyString(attr)
values, ok := mapValues(attr.Value)
if !ok {
return nil, fmt.Errorf("parameter '%s' must be a mapping", name)
}
typ, ok := valueAt(values, "Type")
if !ok {
return nil, fmt.Errorf("parameter '%s' is missing required field 'Type'", name)
}
if typ.Type() != ast.StringType {
return nil, fmt.Errorf("'Type' of parameter '%s' must be a string", name)
}
typeValue, isSSMParameter := typ.(*ast.StringNode).Value, false
if matches := ssmPattern.FindStringSubmatch(typeValue); len(matches) != 0 {
typeValue, isSSMParameter = matches[1], true
}
typeExpr, ok := renderParameterType(typeValue)
if !ok {
return nil, fmt.Errorf("Unrecognized type '%v' for parameter '%s'", typeValue, name)
}
paramRefVar, ok := ctx.parameters[keyString(attr)]
if !ok {
return nil, fmt.Errorf("unknown parameter '%v'", name)
}
paramDefVar := paramRefVar
if isSSMParameter {
paramDefVar, ok = ctx.ssmParameters[keyString(attr)]
if !ok {
return nil, fmt.Errorf("unknown SSM parameter '%v'", name)
}
typeExpr = "string"
}
var defaultValue model.Expression
if def, ok := valueAt(values, "Default"); ok {
v, err := ctx.renderValue(def)
if err != nil {
return nil, err
}
defaultValue = v
}
configDef := &model.Block{
Type: "config",
Labels: []string{paramDefVar.Name, typeExpr},
Body: &model.Body{},
}
if !isSSMParameter {
if defaultValue != nil {
configDef.Body.Items = append(configDef.Body.Items, &model.Attribute{
Name: "default",
Value: defaultValue,
})
}
return []model.BodyItem{configDef}, nil
}
ssmGetter := "getSsmParameterString"
switch typeExpr {
case "number", "list(number)":
return nil, fmt.Errorf("type '%v' is not supported for SSM parameters", typeValue)
case "string":
// OK
default:
ssmGetter = "getSsmParameterList"
}
var getParamValue model.Expression = relativeTraversal(
invoke("aws-native::"+ssmGetter,
objectConsItem("name", model.VariableReference(paramDefVar))),
"value")
if defaultValue != nil {
configDef.Body.Items = append(configDef.Body.Items, &model.Attribute{
Name: "default",
Value: quotedLit(""),
})
getParamValue = &model.ConditionalExpression{
Condition: &model.BinaryOpExpression{
LeftOperand: model.VariableReference(paramDefVar),
Operation: hclsyntax.OpEqual,
RightOperand: quotedLit(""),
},
TrueResult: defaultValue,
FalseResult: getParamValue,
}
}
return []model.BodyItem{
configDef,
&model.Attribute{
Name: paramRefVar.Name,
Value: getParamValue,
},
}, nil
}
// renderMapping renders a CloudFormation mapping as a PCL local variable whose value is the value of the mapping.
func (ctx *renderContext) renderMapping(attr *ast.MappingValueNode) (model.BodyItem, hcl.Diagnostics, error) {
v, ok := ctx.mappings[keyString(attr)]
if !ok {
return nil, nil, fmt.Errorf("unknown mapping '%v'", keyString(attr))
}
m, err := ctx.renderValue(attr.Value)
if err != nil {
return nil, nil, err
}
return &model.Attribute{
Name: v.Name,
Value: m,
}, nil, nil
}
// renderCondition renders a CloudFormation condition as a PCL local variable whose value is the value of the
// condition.
func (ctx *renderContext) renderCondition(attr *ast.MappingValueNode) (model.BodyItem, hcl.Diagnostics, error) {
v, ok := ctx.conditions[keyString(attr)]
if !ok {
return nil, nil, fmt.Errorf("unknown condition '%v'", keyString(attr))
}
m, err := ctx.renderValue(attr.Value)
if err != nil {
return nil, nil, err
}
return &model.Attribute{
Name: v.Name,
Value: m,
}, nil, nil
}
// renderResource renders a CloudFormation resource as a PCL resource.
func (ctx *renderContext) renderResource(attr *ast.MappingValueNode) (model.BodyItem, hcl.Diagnostics, error) {
name := keyString(attr)
values, ok := mapValues(attr.Value)
if !ok {
return nil, nil, fmt.Errorf("resource '%v' must be a mapping", name)
}
resourceVar, ok := ctx.resources[name]
if !ok {
return nil, nil, fmt.Errorf("unknown resource '%v'", name)
}
var token string
var items []model.BodyItem
var diagnostics hcl.Diagnostics
for _, f := range values {
switch keyString(f) {
case "CreationPolicy", "DeletionPolicy", "Metadata", "Properties", "UpdatePolicy", "UpdateReplacePolicy":
subValues, ok := mapValues(f.Value)
if !ok {
return nil, diagnostics, fmt.Errorf("'%v' must be a mapping", keyString(f))
}
for _, sf := range subValues {
keyValue := keyString(sf)
// Properties should never contain a colon. This is only used within metadata which we discard.
if strings.ContainsRune(keyValue, ':') {
continue
}
sv, err := ctx.renderValue(sf.Value)
if err != nil {
return nil, diagnostics, err
}
items = append(items, &model.Attribute{
Name: camel(keyValue),
Value: sv,
})
}
case "DependsOn":
var arr []ast.Node
switch f.Value.Type() {
case ast.StringType:
arr = []ast.Node{f.Value}
case ast.SequenceType:
arr = f.Value.(*ast.SequenceNode).Values
default:
return nil, diagnostics, fmt.Errorf("the \"DependsOn\" attribute for resource '%v' must be a string or list of strings", name)
}
var refs []model.Expression
for _, v := range arr {
if v.Type() != ast.StringType {
return nil, diagnostics, fmt.Errorf("the \"DependsOn\" attribute for resource '%v' must be a string or list of strings", name)
}
resourceName := v.(*ast.StringNode).Value
resourceVar, ok := ctx.resources[resourceName]
if !ok {
return nil, diagnostics, fmt.Errorf("unknown resource '%v'", resourceName)
}
refs = append(refs, model.VariableReference(resourceVar))
}
items = append(items, &model.Block{
Type: "options",
Body: &model.Body{
Items: []model.BodyItem{
&model.Attribute{
Name: "dependsOn",
Value: &model.TupleConsExpression{
Expressions: refs,
},
},
},
},
})
case "Type":
if f.Value.Type() != ast.StringType {
return nil, diagnostics, fmt.Errorf("the \"Type\" of reosurce '%v' must be a string", name)
}
cfType := f.Value.(*ast.StringNode).Value
resourceType := cfType
parts := strings.Split(cfType, "::")
if len(parts) == 3 {
resourceType = fmt.Sprintf("%s::%s::%s", parts[0], strings.ToLower(parts[1]), parts[2])
}
token = resourceToken(resourceType)
if token != "" && !ctx.supportedResources.Has(token) {
diagnostics = append(diagnostics, &hcl.Diagnostic{
Severity: hcl.DiagWarning,
Summary: "Resource not supported",
Detail: fmt.Sprintf("Resource %q is not yet supported by AWS CloudControl API. Code generated for %q is for reference only.", token, resourceVar.Name),
})
}
case "Version":
// Ignore.
default:
return nil, diagnostics, fmt.Errorf("unsupported property '%v' in resource '%v'", f.Key, name)
}
}
if token == "" {
return nil, diagnostics, fmt.Errorf("resource '%v' has no \"Type\" attribute", name)
}
return &model.Block{
Type: "resource",
Labels: []string{resourceVar.Name, token},
Body: &model.Body{Items: items},
}, diagnostics, nil
}
// renderOutput renders a CloudFormation output as a PCL output.
func (ctx *renderContext) renderOutput(attr *ast.MappingValueNode) (model.BodyItem, hcl.Diagnostics, error) {
name := keyString(attr)
values, ok := mapValues(attr.Value)
if !ok {
return nil, nil, fmt.Errorf("output '%v' must be a mapping", name)
}
outputVar, ok := ctx.outputs[name]
if !ok {
return nil, nil, fmt.Errorf("unknown output '%v'", name)
}
// TODO: description, export