-
Notifications
You must be signed in to change notification settings - Fork 43
/
schema.go
1821 lines (1639 loc) · 61.2 KB
/
schema.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-2018, Pulumi Corporation.
//
// 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.
package tfbridge
import (
"context"
"encoding/json"
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"github.com/golang/glog"
pbstruct "github.com/golang/protobuf/ptypes/struct"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
shim "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim/schema"
)
// This file deals with translating between the Pulumi representations of a resource's configuration and state and the
// Terraform shim's representations of the same.
//
// # Terraform Representations
//
// The Terraform shim represents a resource's configuration and state as plain-old Go values. These values may be
// any of the following types:
//
// - nil
// - bool
// - int
// - float64
// - string
// - []interface{}
// - map[string]interface{}
// - Set (state only; exact type varies between shim implementations; see shim.Provider.IsSet)
//
// Unknown values are represented using a sentinel string value (see TerraformUnknownVariableValue).
//
// The Terraform shim also records a schema for each resource & data source that is used to guide the conversion
// process. The schema indicates the type or sub-schema for each of the resource's properties. The schema types
// and their corresponding value types are given below.
//
// Schema Type | TF type | Notes
// ------------+------------------------+------------
// TypeBool | bool |
// TypeInt | int |
// TypeFloat | float |
// TypeString | string |
// TypeList | []interface{} |
// TypeMap | map[string]interface{} | See below for a special case involving object types
// TypeSet | []interface{}, Set | Set values are only present in state
//
// Note that object types are not present in the set of schema types. Instead, they exist either at the resource level
// or as the element type of a List, Map, or Set (concretely, the type of schema.Elem() will be shim.Resource). As a
// special case, the value of a TypeMap property with an object element type is represented as a single-element
// []interface{} where the single element is the object value.
//
// # Pulumi Representations
//
// Pulumi represents a resource's configuration and state as resource.PropertyValue values. These values are
// JSON-like with a few extensions. The only extensions that are relevant to this code are unknowns, assets, and
// archives. Unknowns represent unknown values, while assets and archives represent flat binary or archive data
// (e.g. .tar or .zip files), respectively.
//
// To improve the user experience of the generated SDKs, the bridge also carries optional overlays for resources.
// These overlays control various aspects of the conversion process, notably name translation, asset translation,
// and single-element list projection.
//
// # Conversion Process
//
// The conversion process is informed by the kind of conversion to perform, the Terraform schema for the value,
// and the tfbridge overlays for the value.
//
// In most cases, mapping between the value spaces is straightforward, and follows these rules:
//
// Pulumi type | TF type(s) | Notes
// ------------+----------------------------+-----------------------
// null | nil |
// bool | bool |
// number | float64, int | for config conversion, numbers are converted per the TF schema
// string | string, bool, float64, int | for state conversion, strings may be coerced per schema+overlays
// array | []interface{} |
// object | map[string]interface{} | keys may be mapped between snake and Pascal case per schema+overlays
// asset | string, []byte | file path or literal contents per overlays
// archive | string, []byte | file path or literal contents per overlays
// unknown | string | always the unknown sentinel string value
//
// Certain properties that are represented by the shim as single-element `[]interface{}` values may be represented by
// Pulumi as their single element. This is controlled by the Terraform schema and the tfbridge overlays (see
// IsMaxItemsOne for details).
//
// ## Pulumi Inputs -> TF Config Conversion
//
// In addition to the usual conversion operation, config conversion has the onerous task of applying default values
// for missing properties if a default is present in the TF schema or tfbridge overlays. Default application is a
// relatively complex process. To determine the default value for a missing property:
//
// 1. If setting a value for the property would cause a conflict with other properties per the TF schema,
// then the property has no default value.
// 2. If the property is marked as removed, it has no default value.
// 3. If the property's overlay contains default value information:
// a. If there is an old value for property and that value was a default value, use the old value.
// This ensures that non-deterministic defaults (e.g. autonames) are not recalculated.
// b. If the default value is sourced from an envvar, read the envvar.
// c. If the default value is source from provider config, grab it from the indicated config value.
// d. If the default value is literal, use the literal value.
// e. If the default value is computed by a function, call the function.
// 4. If the property's TF schema has a default value:
// a. If there is an old value for property and that value was a default value, use the old value.
// This ensures that non-deterministic defaults (e.g. autonames) are not recalculated.
// b. Otherwise, the value is literal. Use the literal value.
//
// Each object-typed value contains metadata about the properties that were set using default values under a
// special key ("__defaults"). This information is consulted in steps 3a and 4a to determine whether or not to
// propagate the old value for a property as a default.
//
// Config conversion also records which properties were originally assets or archives so that the state converter
// can round-trip the values of those properties as assets/archives.
//
// The entry point for input to config conversion is MakeTerraformConfig.
//
// ## TF State/Config -> Pulumi Outputs Conversion
//
// In order to provide full-fidelity round-tripping of properties that were presented in the config as assets or
// archives, the state converter accepts a mapping from properties to asset/archive values. The converter consults
// consults
//
// The entry point for state/config to output conversion is MakeTerraformResult.
//
// ## Pulumi Outputs -> TF State Conversion
//
// Output to state conversion follows the same rules as input to config conversion, but does not apply defaults or
// record asset and archive values.
//
// # Additional Notes
//
// The process for converting between Pulumi and Terraform values is rather complicated, and occasionally has some
// pretty frustrating impedance mismatches with Terraform itself. These mismatches have become more pronounced as
// Terraform has evolved, and mostly seem to be due to the fact that tfbridge interfaces with Terraform providers
// at a different layer than Terraform itself. Terraform speaks to resource providers over a well-defined gRPC
// interface that as of TF 0.12 provides access to the provider's schema as well as config validation, plan, and
// apply operations (plus a few other sundries). tfbridge, however, interacts with the Terraform plugin SDK, which
// sits on top of the gRPC interface. As a result, the inputs tfbridge passes to the plugin SDK's APIs are not
// subject to the preprocessing that is performed when Terraform interacts with the provider via the gRPC API.
//
// If tfbridge also used the gRPC interface (ideally in-memory or in-process), its implementation may be simpler.
// With that approach, tfbridge would be responsible for producing config and state in the same shape as the Terraform
// CLI and expected by the gRPC interface, and that config and state would be subject to the same pipeline as that
// produced by the Terraform CLI. The major blocker to this design is our current approach to default values, which
// relies on visibility into default values and `ConflictsWith` information that is not exposed by the gRPC-level
// provider schema. It is unclear what the overall effect of dropping this approach to default values would be, but
// one very likely change is that default values from providers would no longer be rendered as part of diffs in the
// Pulumi CLI. It may be possible to remedy that experience through changes to the CLI.
//
// There is something approaching a prototype of the above approach in pkg/tfshim/tfplugin5. That code has bitrotted
// somewhat since its creation, as it is not actively used in production.
// TerraformUnknownVariableValue is the sentinal defined in github.com/hashicorp/terraform/configs/hcl2shim,
// representing a variable whose value is not known at some particular time. The value is duplicated here in
// order to prevent an additional dependency - it is unlikely to ever change upstream since that would break
// rather a lot of things.
const TerraformUnknownVariableValue = "74D93920-ED26-11E3-AC10-0800200C9A66"
// defaultsKey is the name of the input property that is used to track which property keys were populated using
// default values from the resource's schema. This information is used to inform which input properties should be
// populated using old defaults in subsequent updates. When populating the default value for an input property, the
// property's old value will only be used as the default if the property's key is present in the defaults list for
// the old property bag.
const defaultsKey = "__defaults"
// AssetTable is used to record which properties in a call to MakeTerraformInputs were assets so that they can be
// marshaled back to assets by MakeTerraformOutputs.
type AssetTable map[*SchemaInfo]resource.PropertyValue
// ErrSchemaDefaultValue is used internally to avoid a panic in pf/schemashim.DefaultValue().
// See https://github.com/pulumi/pulumi-terraform-bridge/issues/1329
var ErrSchemaDefaultValue = fmt.Errorf("default values not supported")
// nameRequiresDeleteBeforeReplace returns true if the given set of resource inputs includes an autonameable
// property with a value that was not populated by the autonamer.
func nameRequiresDeleteBeforeReplace(news resource.PropertyMap, olds resource.PropertyMap,
tfs shim.SchemaMap, resourceInfo *ResourceInfo,
) bool {
fields := resourceInfo.Fields
defaults, hasDefaults := news[defaultsKey]
if !hasDefaults || !defaults.IsArray() {
// If there is no list of properties that were populated using defaults, consider the resource autonamed.
// This avoids setting delete-before-replace for resources that were created before the defaults list existed.
return false
}
hasDefault := map[resource.PropertyKey]bool{}
for _, key := range defaults.ArrayValue() {
if !key.IsString() {
continue
}
hasDefault[resource.PropertyKey(key.StringValue())] = true
}
// These are a list of Pulumi named fields that we care about comparing to try
// and override the deleteBeforeReplace e.g. name or namePrefix
// if any of these values change then we can assume we can
if len(resourceInfo.UniqueNameFields) > 0 {
for _, name := range resourceInfo.UniqueNameFields {
key := resource.PropertyKey(name)
_, _, psi := getInfoFromPulumiName(key, tfs, fields)
oldVal := olds[key]
newVal := news[key]
if !oldVal.DeepEquals(newVal) {
return false
}
if psi != nil && psi.HasDefault() && psi.Default.AutoNamed && hasDefault[key] {
return false
}
}
return true
}
for key := range news {
_, _, psi := getInfoFromPulumiName(key, tfs, fields)
if psi != nil && psi.HasDefault() && psi.Default.AutoNamed && !hasDefault[key] {
return true
}
}
return false
}
func multiEnvDefault(names []string, dv interface{}) interface{} {
for _, n := range names {
if v := os.Getenv(n); v != "" {
return v
}
}
return dv
}
func getSchema(m shim.SchemaMap, key string) shim.Schema {
if m == nil {
return nil
}
return m.Get(key)
}
func elemSchemas(sch shim.Schema, ps *SchemaInfo) (shim.Schema, *SchemaInfo) {
var esch shim.Schema
if sch != nil {
switch e := sch.Elem().(type) {
case shim.Schema:
esch = e
case shim.Resource:
esch = (&schema.Schema{Elem: e}).Shim()
default:
esch = nil
}
}
var eps *SchemaInfo
if ps != nil {
eps = ps.Elem
}
return esch, eps
}
type conversionContext struct {
Ctx context.Context
ComputeDefaultOptions ComputeDefaultOptions
ProviderConfig resource.PropertyMap
ApplyDefaults bool
ApplyTFDefaults bool
Assets AssetTable
UnknownCollectionsSupported bool
}
type makeTerraformInputsOptions struct {
DisableDefaults bool
DisableTFDefaults bool
UnknownCollectionsSupported bool
}
func makeTerraformInputsWithOptions(
ctx context.Context, instance *PulumiResource, config resource.PropertyMap,
olds, news resource.PropertyMap, tfs shim.SchemaMap, ps map[string]*SchemaInfo,
opts makeTerraformInputsOptions,
) (map[string]interface{}, AssetTable, error) {
cdOptions := ComputeDefaultOptions{}
if instance != nil {
cdOptions = ComputeDefaultOptions{
PriorState: olds,
Properties: instance.Properties,
Seed: instance.Seed,
Autonaming: instance.Autonaming,
URN: instance.URN,
}
}
cctx := &conversionContext{
Ctx: ctx,
ComputeDefaultOptions: cdOptions,
ProviderConfig: config,
ApplyDefaults: !opts.DisableDefaults,
ApplyTFDefaults: !opts.DisableTFDefaults,
Assets: AssetTable{},
UnknownCollectionsSupported: opts.UnknownCollectionsSupported,
}
inputs, err := cctx.makeTerraformInputs(olds, news, tfs, ps)
if err != nil {
return nil, nil, err
}
return inputs, cctx.Assets, err
}
// Deprecated: missing some important functionality, use makeTerraformInputsWithOptions instead.
func MakeTerraformInputs(
ctx context.Context, instance *PulumiResource, config resource.PropertyMap,
olds, news resource.PropertyMap, tfs shim.SchemaMap, ps map[string]*SchemaInfo,
) (map[string]interface{}, AssetTable, error) {
return makeTerraformInputsWithOptions(ctx, instance, config, olds, news, tfs, ps, makeTerraformInputsOptions{})
}
// makeSingleTerraformInput converts a single Pulumi property value into a plain go value suitable for use by Terraform.
// makeSingleTerraformInput does not apply any defaults or other transformations.
func makeSingleTerraformInput(
ctx context.Context, name string, val resource.PropertyValue, tfs shim.Schema, ps *SchemaInfo,
) (interface{}, error) {
cctx := &conversionContext{
Ctx: ctx,
ComputeDefaultOptions: ComputeDefaultOptions{},
ProviderConfig: nil,
ApplyDefaults: false,
ApplyTFDefaults: false,
Assets: AssetTable{},
UnknownCollectionsSupported: false,
}
return cctx.makeTerraformInput(name, resource.NewNullProperty(), val, tfs, ps)
}
// makeTerraformInput takes a single property plus custom schema info and does whatever is necessary
// to prepare it for use by Terraform. Note that this function may have side effects, for instance
// if it is necessary to spill an asset to disk in order to create a name out of it. Please take
// care not to call it superfluously!
func (ctx *conversionContext) makeTerraformInput(
name string,
old, v resource.PropertyValue,
tfs shim.Schema,
ps *SchemaInfo,
) (interface{}, error) {
// For TypeList or TypeSet with MaxItems==1, we will have projected as a scalar
// nested value, and need to wrap it into a single-element array before passing to
// Terraform.
if IsMaxItemsOne(tfs, ps) {
wrap := func(val resource.PropertyValue) resource.PropertyValue {
if val.IsNull() {
return resource.NewArrayProperty([]resource.PropertyValue{})
}
// If we are expecting a value of type `[T]` where `T != TypeList`
// and we already see `[T]`, we see that `v` is already the right
// shape and return as is.
//
// This is possible when the old state is from a previous version
// with `MaxItemsOne=false` but the new state has
// `MaxItemsOne=true`.
if elem := tfs.Elem(); elem != nil {
if elem, ok := elem.(shim.Schema); ok &&
// If the underlying type is not a list or set,
// but the value is a list, we just return as is.
!(elem.Type() == shim.TypeList || elem.Type() == shim.TypeSet) &&
val.IsArray() {
return val
}
}
return resource.NewArrayProperty([]resource.PropertyValue{val})
}
old = wrap(old)
v = wrap(v)
}
wrapError := func(v any, err error) (any, error) {
if err == nil {
return v, nil
}
return v, fmt.Errorf("%s: %w", name, err)
}
// If there is a custom transform for this value, run it before processing the value.
if ps != nil && ps.Transform != nil {
nv, err := ps.Transform(v)
if err != nil {
return wrapError(nv, err)
}
v = nv
}
if tfs == nil {
tfs = (&schema.Schema{}).Shim()
}
switch {
case v.IsNull():
return nil, nil
case v.IsBool():
switch tfs.Type() {
case shim.TypeString:
if v.BoolValue() {
return "true", nil
}
return "false", nil
default:
return v.BoolValue(), nil
}
case v.IsNumber():
switch tfs.Type() {
case shim.TypeFloat:
return v.NumberValue(), nil
case shim.TypeString:
return strconv.FormatFloat(v.NumberValue(), 'f', -1, 64), nil
default: // By default, we return ints
return int(v.NumberValue()), nil
}
case v.IsString():
switch tfs.Type() {
case shim.TypeInt:
v, err := wrapError(strconv.ParseInt(v.StringValue(), 10, 64))
// The plugin sdk asserts against the type - need this to be an int.
return int(v.(int64)), err
default:
return v.StringValue(), nil
}
case v.IsArray():
var oldArr []resource.PropertyValue
if old.IsArray() {
oldArr = old.ArrayValue()
}
etfs, eps := elemSchemas(tfs, ps)
var arr []interface{}
for i, elem := range v.ArrayValue() {
var oldElem resource.PropertyValue
if i < len(oldArr) {
oldElem = oldArr[i]
}
elemName := fmt.Sprintf("%v[%v]", name, i)
e, err := ctx.makeTerraformInput(elemName, oldElem, elem, etfs, eps)
if err != nil {
return nil, err
}
if ps != nil && ps.SuppressEmptyMapElements != nil && *ps.SuppressEmptyMapElements {
if eMap, ok := e.(map[string]interface{}); ok && len(eMap) > 0 {
arr = append(arr, e)
}
} else {
arr = append(arr, e)
}
}
return arr, nil
case v.IsAsset():
// We require that there be asset information, otherwise an error occurs.
if ps == nil || ps.Asset == nil {
return nil, errors.Errorf("unexpected asset %s", name)
} else if !ps.Asset.IsAsset() {
return nil, errors.Errorf("expected an asset, but %s is not an asset", name)
}
if ctx.Assets != nil {
_, has := ctx.Assets[ps]
contract.Assertf(!has, "duplicate schema info for asset")
ctx.Assets[ps] = v
}
return ps.Asset.TranslateAsset(v.AssetValue())
case v.IsArchive():
// We require that there be archive information, otherwise an error occurs.
if ps == nil || ps.Asset == nil {
return nil, errors.Errorf("unexpected archive %s", name)
}
if ctx.Assets != nil {
_, has := ctx.Assets[ps]
contract.Assertf(!has, "duplicate schema info for asset")
ctx.Assets[ps] = v
}
return ps.Asset.TranslateArchive(v.ArchiveValue())
case v.IsObject():
var oldObject resource.PropertyMap
if old.IsObject() {
oldObject = old.ObjectValue()
}
var tfflds shim.SchemaMap
if tfs != nil {
if r, ok := tfs.Elem().(shim.Resource); ok {
tfflds = r.Schema()
}
}
if tfflds != nil {
var psflds map[string]*SchemaInfo
if ps != nil {
psflds = ps.Fields
}
obj, err := ctx.makeObjectTerraformInputs(oldObject, v.ObjectValue(), tfflds, psflds)
if err != nil {
return nil, err
}
if tfs.Type() == shim.TypeMap {
// If we have schema information that indicates that this value is being
// presented to a map-typed field whose Elem is a shim.Resource, wrap the
// value in an array in order to work around a bug in Terraform.
//
// TODO[pulumi/pulumi-terraform-bridge#1828]: This almost certainly stems from
// a bug in the bridge's implementation and not terraform's implementation.
return []interface{}{obj}, nil
}
return obj, nil
}
etfs, eps := elemSchemas(tfs, ps)
return ctx.makeMapTerraformInputs(oldObject, v.ObjectValue(), etfs, eps)
case v.IsComputed() || v.IsOutput():
// If any variables are unknown, we need to mark them in the inputs so the config map treats it right. This
// requires the use of the special UnknownVariableValue sentinel in Terraform, which is how it internally stores
// interpolated variables whose inputs are currently unknown.
return makeTerraformUnknown(tfs, ctx.UnknownCollectionsSupported), nil
default:
contract.Failf("Unexpected value marshaled: %v", v)
return nil, nil
}
}
// makeTerraformInputs takes a property map plus custom schema info and does whatever is necessary
// to prepare it for use by Terraform. Note that this function may have side effects, for instance
// if it is necessary to spill an asset to disk in order to create a name out of it. Please take
// care not to call it superfluously!
func (ctx *conversionContext) makeTerraformInputs(
olds, news resource.PropertyMap,
tfs shim.SchemaMap,
ps map[string]*SchemaInfo,
) (map[string]interface{}, error) {
return ctx.makeObjectTerraformInputs(olds, news, tfs, ps)
}
// Should only be called from inside makeTerraformInputs. Variation for makeTerraformInputs used
// when the schema indicates that the code is handling a map[string,X] case and not an object.
func (ctx *conversionContext) makeMapTerraformInputs(
olds, news resource.PropertyMap,
tfsElement shim.Schema,
psElement *SchemaInfo,
) (map[string]interface{}, error) {
result := make(map[string]interface{})
for key, value := range news {
// Map keys always preserved as-is, no translation necessary.
name := string(key)
var old resource.PropertyValue
if ctx.ApplyDefaults && olds != nil {
old = olds[key]
}
v, err := ctx.makeTerraformInput(name, old, value, tfsElement, psElement)
if err != nil {
return nil, err
}
result[name] = v
glog.V(9).Infof("Created Terraform input: %v = %v", name, v)
}
if glog.V(5) {
for k, v := range result {
glog.V(5).Infof("Terraform input %v = %#v", k, v)
}
}
return result, nil
}
// Should only be called from inside makeTerraformInputs. This variation should only be
// handling the case when an object type is expected. The case when map types are expected
// or the schema is lost and the translation is not sure of the expected type is handled
// by makeMapTerraformInputs.
func (ctx *conversionContext) makeObjectTerraformInputs(
olds, news resource.PropertyMap,
tfs shim.SchemaMap,
ps map[string]*SchemaInfo,
) (map[string]interface{}, error) {
result := make(map[string]interface{})
tfAttributesToPulumiProperties := make(map[string]string)
// Enumerate the inputs provided and add them to the map using their Terraform names.
for key, value := range news {
// If this is a reserved property, ignore it.
switch key {
case defaultsKey, metaKey:
continue
}
// First translate the Pulumi property name to a Terraform name.
name, tfi, psi := getInfoFromPulumiName(key, tfs, ps)
contract.Assertf(name != "", `Object properties cannot be empty`)
if _, duplicate := result[name]; duplicate {
// If multiple Pulumi `key`s map to the same Terraform attribute `name`, then
// this function's output is dependent on the iteration order of `news`, and
// thus non-deterministic. Values clober each other when assigning to
// `result[name]`.
//
// We fail with an "internal" error because this duplication should have been
// caught when `make tfgen` was run.
//
// For context, see:
// - https://github.com/pulumi/pulumi-terraform-bridge/issues/774
// - https://github.com/pulumi/pulumi-terraform-bridge/issues/773
return nil, fmt.Errorf(
"internal: Pulumi property '%s' mapped non-uniquely to Terraform attribute '%s' (duplicates Pulumi key '%s')",
key, name, tfAttributesToPulumiProperties[name])
}
tfAttributesToPulumiProperties[name] = string(key)
var old resource.PropertyValue
if ctx.ApplyDefaults && olds != nil {
old = olds[key]
}
// And then translate the property value.
v, err := ctx.makeTerraformInput(name, old, value, tfi, psi)
if err != nil {
return nil, err
}
result[name] = v
glog.V(9).Infof("Created Terraform input: %v = %v", name, v)
}
// Now enumerate and propagate defaults if the corresponding values are still missing.
if err := ctx.applyDefaults(result, olds, news, tfs, ps); err != nil {
return nil, err
}
if glog.V(5) {
for k, v := range result {
glog.V(5).Infof("Terraform input %v = %#v", k, v)
}
}
return result, nil
}
func buildExactlyOneOfsWith(result map[string]interface{}, tfs shim.SchemaMap) map[string]struct{} {
exactlyOneOf := make(map[string]struct{})
if tfs != nil {
tfs.Range(func(name string, sch shim.Schema) bool {
if _, has := result[name]; has {
// `name` is present, so mark any names that are declared to
// exactlyOneOf with `name` for exclusion.
for _, exclusion := range sch.ExactlyOneOf() {
exactlyOneOf[exclusion] = struct{}{}
}
} else {
// `name` is not present, so mark it for exclusion if any fields
// that exactlyOneOf with `name` are present.
for _, exclusion := range sch.ExactlyOneOf() {
if _, has := result[exclusion]; has {
exactlyOneOf[name] = struct{}{}
break
}
}
}
return true
})
}
return exactlyOneOf
}
func buildConflictsWith(result map[string]interface{}, tfs shim.SchemaMap) map[string]struct{} {
conflictsWith := make(map[string]struct{})
if tfs != nil {
tfs.Range(func(name string, sch shim.Schema) bool {
if _, has := result[name]; has {
// `name` is present, so mark any names that are declared to
// conflict with `name` for exclusion.
for _, conflictingName := range sch.ConflictsWith() {
conflictsWith[conflictingName] = struct{}{}
}
} else {
// `name` is not present, so mark it for exclusion if any fields
// that conflict with `name` are present.
for _, conflictingName := range sch.ConflictsWith() {
if _, has := result[conflictingName]; has {
conflictsWith[name] = struct{}{}
break
}
}
}
return true
})
}
return conflictsWith
}
func (ctx *conversionContext) applyDefaults(
result map[string]interface{},
olds, news resource.PropertyMap,
tfs shim.SchemaMap,
ps map[string]*SchemaInfo,
) error {
if !ctx.ApplyDefaults {
return nil
}
// Create an array to track which properties are defaults.
newDefaults := []interface{}{}
// Pull the list of old defaults if any. If there is no list, then we will treat all old values as being usable
// for new defaults. If there is a list, we will only propagate defaults that were themselves defaults.
useOldDefault := func(key resource.PropertyKey) bool { return true }
if oldDefaults, ok := olds[defaultsKey]; ok {
oldDefaultSet := make(map[resource.PropertyKey]bool)
for _, k := range oldDefaults.ArrayValue() {
oldDefaultSet[resource.PropertyKey(k.StringValue())] = true
}
useOldDefault = func(key resource.PropertyKey) bool { return oldDefaultSet[key] }
}
// Compute any names for which setting a default would cause a conflict.
conflictsWith := buildConflictsWith(result, tfs)
exactlyOneOf := buildExactlyOneOfsWith(result, tfs)
// First, attempt to use the overlays.
for name, info := range ps {
if info.Removed {
continue
}
if _, conflicts := conflictsWith[name]; conflicts {
continue
}
if _, exactlyOneOfConflicts := exactlyOneOf[name]; exactlyOneOfConflicts {
continue
}
sch := getSchema(tfs, name)
if sch != nil && (sch.Removed() != "" || sch.Deprecated() != "" && !sch.Required()) {
continue
}
if _, has := result[name]; !has && info.HasDefault() {
var defaultValue interface{}
var source string
// If we already have a default value from a previous version of this resource, use that instead.
key, tfi, psi := getInfoFromTerraformName(name, tfs, ps, false)
if old, hasold := olds[key]; hasold && useOldDefault(key) {
v, err := ctx.makeTerraformInput(name, resource.PropertyValue{},
old, tfi, psi)
if err != nil {
return err
}
defaultValue, source = v, "old default"
} else if envVars := info.Default.EnvVars; len(envVars) != 0 {
var err error
v := multiEnvDefault(envVars, info.Default.Value)
if str, ok := v.(string); ok && sch != nil {
switch sch.Type() {
case shim.TypeBool:
v = false
if str != "" {
if v, err = strconv.ParseBool(str); err != nil {
return err
}
}
case shim.TypeInt:
v = int(0)
if str != "" {
iv, iverr := strconv.ParseInt(str, 0, 0)
if iverr != nil {
return iverr
}
v = int(iv)
}
case shim.TypeFloat:
v = float64(0.0)
if str != "" {
if v, err = strconv.ParseFloat(str, 64); err != nil {
return err
}
}
case shim.TypeString:
// nothing to do
default:
return errors.Errorf("unknown type for default value: %v", sch.Type())
}
}
defaultValue, source = v, "env vars"
} else if configKey := info.Default.Config; configKey != "" {
if v := ctx.ProviderConfig[resource.PropertyKey(configKey)]; !v.IsNull() {
tv, err := ctx.makeTerraformInput(name, resource.PropertyValue{}, v, tfi, psi)
if err != nil {
return err
}
defaultValue, source = tv, "config"
}
} else if info.Default.Value != nil {
v := resource.NewPropertyValue(info.Default.Value)
tv, err := ctx.makeTerraformInput(name, resource.PropertyValue{}, v, tfi, psi)
if err != nil {
return err
}
defaultValue, source = tv, "Pulumi schema"
} else if compute := info.Default.ComputeDefault; compute != nil {
cdOpts := ctx.ComputeDefaultOptions
if old, hasold := olds[key]; hasold {
cdOpts.PriorValue = old
}
v, err := compute(ctx.Ctx, cdOpts)
if err != nil {
return err
}
defaultValue, source = v, "func"
} else if from := info.Default.From; from != nil {
v, err := from(&PulumiResource{
URN: ctx.ComputeDefaultOptions.URN,
Properties: ctx.ComputeDefaultOptions.Properties,
Seed: ctx.ComputeDefaultOptions.Seed,
Autonaming: ctx.ComputeDefaultOptions.Autonaming,
})
if err != nil {
return err
}
defaultValue, source = v, "func"
}
if defaultValue != nil {
glog.V(9).Infof("Created Terraform input: %v = %v (from %s)", name, defaultValue, source)
result[name] = defaultValue
newDefaults = append(newDefaults, key)
// Expand the conflicts and exactlyOneOf map
if sch != nil {
for _, conflictingName := range sch.ConflictsWith() {
conflictsWith[conflictingName] = struct{}{}
}
for _, exactlyOneOfName := range sch.ExactlyOneOf() {
exactlyOneOf[exactlyOneOfName] = struct{}{}
}
}
}
}
}
// Next, populate defaults from the Terraform schema.
if tfs != nil && ctx.ApplyTFDefaults {
var valueErr error
tfs.Range(func(name string, sch shim.Schema) bool {
if sch.Removed() != "" {
return true
}
if sch.Deprecated() != "" && !sch.Required() {
return true
}
if _, conflicts := conflictsWith[name]; conflicts {
return true
}
if _, exactlyOneOfConflict := exactlyOneOf[name]; exactlyOneOfConflict {
return true
}
// If a conflicting field has a default value, don't set the default for the current field
for _, conflictingName := range sch.ConflictsWith() {
if conflictingSchema, exists := tfs.GetOk(conflictingName); exists {
dv, _ := conflictingSchema.DefaultValue()
if dv != nil {
return true
}
}
}
for _, exactlyOneOfName := range sch.ExactlyOneOf() {
// If any *other* ExactlyOneOf keys have a default value, don't set the default for the current field
if exactlyOneOfName == name {
continue
}
if exactlyOneSchema, exists := tfs.GetOk(exactlyOneOfName); exists {
dv, _ := exactlyOneSchema.DefaultValue()
if dv != nil {
return true
}
}
}
if _, has := result[name]; !has {
var source string
// Check for a default value from Terraform. If there is not default from terraform, skip this name.
dv, err := sch.DefaultValue()
if err != nil {
valueErr = err
return false
} else if dv == nil {
return true
}
// Next, if we already have a default value from a previous version of this
// resource, use that instead.
key, tfi, psi := getInfoFromTerraformName(name, tfs, ps, false)
if old, hasold := olds[key]; hasold && useOldDefault(key) {
v, err := ctx.makeTerraformInput(name, resource.PropertyValue{}, old, tfi, psi)
if err != nil {
valueErr = err
return false
}
dv, source = v, "old default"
} else {
source = "Terraform schema"
}
if dv != nil {
glog.V(9).Infof("Created Terraform input: %v = %v (from %s)", name, dv, source)
result[name] = dv
newDefaults = append(newDefaults, key)
}
}
return true
})
if valueErr != nil {
return valueErr
}
}
sort.Slice(newDefaults, func(i, j int) bool {
return newDefaults[i].(resource.PropertyKey) < newDefaults[j].(resource.PropertyKey)
})
result[defaultsKey] = newDefaults
return nil
}
// makeTerraformUnknownElement creates an unknown value to be used as an element of a list or set using the given
// element schema to guide the shape of the value.
func makeTerraformUnknownElement(elem interface{}) interface{} {
// If we have no element schema, just return a simple unknown.
if elem == nil {
return TerraformUnknownVariableValue
}
switch e := elem.(type) {
case shim.Schema:
// If the element uses a normal schema, defer to makeTerraformUnknown.
return makeTerraformUnknown(e, false)
case shim.Resource:
// If the element uses a resource schema, fill in unknown values for any required properties.
res := make(map[string]interface{})
e.Schema().Range(func(k string, v shim.Schema) bool {
if v.Required() {
res[k] = makeTerraformUnknown(v, false)
}
return true
})
return res
default:
return TerraformUnknownVariableValue
}
}
// makeTerraformUnknown creates an unknown value with the shape indicated by the given schema.
//
// It is important that we use the TF schema (if available) to decide what shape the unknown value should have:
// e.g. TF does not play nicely with unknown lists, instead expecting a list of unknowns.
func makeTerraformUnknown(tfs shim.Schema, unknownCollectionsSupported bool) interface{} {