-
Notifications
You must be signed in to change notification settings - Fork 161
/
resource.go
916 lines (781 loc) · 25.3 KB
/
resource.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
package provider
import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/chr4/pwgen"
"github.com/cycloidio/terracognita/errcode"
"github.com/cycloidio/terracognita/filter"
"github.com/cycloidio/terracognita/log"
"github.com/cycloidio/terracognita/tag"
"github.com/cycloidio/terracognita/writer"
awsdocs "github.com/cycloidio/tfdocs/providers/aws"
googledocs "github.com/cycloidio/tfdocs/providers/google"
tfdocs "github.com/cycloidio/tfdocs/resource"
"github.com/hashicorp/terraform/configs/configschema"
"github.com/hashicorp/terraform/configs/hcl2shim"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/providers"
"github.com/hashicorp/terraform/states"
"github.com/hashicorp/terraform/terraform"
"github.com/pkg/errors"
"github.com/zclconf/go-cty/cty"
)
//go:generate mockgen -destination=../mock/resource.go -mock_names=Resource=Resource -package mock github.com/cycloidio/terracognita/provider Resource
// Resource represents the minimal information needed to
// define a Provider resource
type Resource interface {
// ID is the ID of the Resource
ID() string
// Type is the type of resource (ex: aws_instance)
Type() string
// InstanceState is the Terraform state of the resource
// it contains important elements like `Attributes`
InstanceState() *terraform.InstanceState
// Name is the resource name given by Terracognita
Name() string
// TFResource is the definition of that resource
TFResource() *schema.Resource
// Data is the actual data of the Resource
Data() *schema.ResourceData
// Provider is the Provider of that Resource
Provider() Provider
// ImportResourceState imports the Resource state
// to the Resource and could return []Resource if
// it imported more than one state, this list does not
// include the actual Resource on parameters, so if
// len([]Resource) == 0 means only the Resource is imported
ImportState() ([]Resource, error)
// Read read the remote information of the Resource to the
// state and calculates the ResourceInstanceObject
Read(f *filter.Filter) error
// State calculates the state of the Resource and
// writes it to w
State(w writer.Writer) error
// HCL returns the HCL configuration of the Resource and
// writes it to HCL
HCL(w writer.Writer) error
// InstanceInfo returns the InstanceInfo of this Resource
InstanceInfo() *terraform.InstanceInfo
// CoreConfigSchema returns the configschema.Block of the
// Resource
CoreConfigSchema() *configschema.Block
// ResourceInstanceObject is the calculated states.ResourceInstanceObject
// after 'Read' has been called
ResourceInstanceObject() *states.ResourceInstanceObject
// AttributesReference return the list of possible value
// to be interpolated with the resource
AttributesReference() ([]string, error)
}
// resources is a general implementation of Resource interface
// that fulfills all the usecases for Terracognita
type resource struct {
id string
// resourceType is the type of resource (ex: aws_instance)
// as type is a reserved word resourceType is used on private
resourceType string
tfResource *schema.Resource
data *schema.ResourceData
state *terraform.InstanceState
provider Provider
// The name it has on the config
// so it can be the same on the HCL
// and State
configName string
resourceInstanceObject *states.ResourceInstanceObject
}
var (
autogeneratedAWSResourcesRe = regexp.MustCompile(`^aws:(?:autoscaling|cloudformation)`)
)
// NewResource returns an implementation of the Resource
func NewResource(id, rt string, p Provider) Resource {
return &resource{
id: id,
resourceType: rt,
provider: p,
}
}
func (r *resource) AttributesReference() ([]string, error) {
var (
res = new(tfdocs.Resource)
err error
)
switch r.provider.String() {
case "aws":
res, err = awsdocs.GetResource(r.resourceType)
case "google":
res, err = googledocs.GetResource(r.resourceType)
}
result := make([]string, len(res.Attributes))
for i, attribute := range res.Attributes {
result[i] = attribute.Name
}
return result, err
}
func (r *resource) ID() string { return r.id }
func (r *resource) Type() string { return r.resourceType }
func (r *resource) Name() string { return r.configName }
func (r *resource) InstanceState() *terraform.InstanceState { return r.state }
func (r *resource) TFResource() *schema.Resource {
if r.tfResource != nil {
return r.tfResource
}
tfr, ok := r.provider.TFProvider().ResourcesMap[r.resourceType]
if !ok {
panic(fmt.Sprintf("the resource %s does not exists on TF", r.resourceType))
}
r.tfResource = tfr
return r.tfResource
}
func (r *resource) Data() *schema.ResourceData {
if r.data == nil {
r.data = r.TFResource().Data(nil)
}
return r.data
}
func (r *resource) Provider() Provider { return r.provider }
func (r *resource) ImportState() ([]Resource, error) {
logger := log.Get()
// If it does not support import do not try
if r.TFResource().Importer == nil {
logger.Log("func", "ImportState", "resource", r.Type(), "msg", "This resource it's not Importable")
return nil, nil
}
newInstanceStates, err := r.provider.TFProvider().ImportState(r.InstanceInfo(), r.ID())
if err != nil {
return nil, errors.Wrapf(err, "could not import resource %s with id %s", r.resourceType, r.id)
}
resources := make([]Resource, 0, len(newInstanceStates)-1)
// We assume that the first state is the one for this Resource
// so the following ones after the first one are from other types
// and are, for that reason, other Resources which should be returned
for i, is := range newInstanceStates {
// copy the ID again just to be sure it wasn't missed
is.Attributes["id"] = is.ID
resourceType := is.Ephemeral.Type
if resourceType == "" {
resourceType = r.Type()
}
if i != 0 {
res := NewResource(is.ID, resourceType, r.provider)
res.(*resource).state = is
resources = append(resources, res)
} else {
r.state = is
}
}
return resources, nil
}
func (r *resource) Read(f *filter.Filter) error {
// If we did not need the 'data' this should be
// r.provider.TFProvider().RefreshWithoutUpgrade()
// but that way we would not have the data and we need
// it to generate the HCL
newInstanceState, data, err := r.refreshWithoutUpgrade(r.state, r.provider.TFClient())
if err != nil {
return err
}
r.state = newInstanceState
// The old provider API used an empty id to signal that the remote
// object appears to have been deleted, but our new protocol expects
// to see a null value (in the cty sense) in that case.
if newInstanceState == nil || newInstanceState.ID == "" {
return errors.Wrapf(errcode.ErrProviderResourceNotRead, "the resource %q with ID %q did not return an ID", r.resourceType, r.id)
}
r.data = data
// Some resources can not be filtered by tags,
// so we have to do it manually
// it's not all of them though
for _, t := range f.Tags {
if v, ok := r.data.GetOk(fmt.Sprintf("%s.%s", r.Provider().TagKey(), t.Name)); ok && v.(string) != t.Value {
return errors.WithStack(errcode.ErrProviderResourceDoNotMatchTag)
}
}
// Filter out autogenerated resources from AWS
if v, ok := r.data.GetOk(r.Provider().TagKey()); ok {
for k := range v.(map[string]interface{}) {
if autogeneratedAWSResourcesRe.MatchString(k) {
return errors.WithStack(errcode.ErrProviderResourceAutogenerated)
}
}
}
// helper/schema should always copy the ID over, but do it again just to be safe
newInstanceState.Attributes["id"] = newInstanceState.ID
newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(newInstanceState.Attributes, r.CoreConfigSchema().ImpliedType())
if err != nil {
return err
}
// In case it's not Imported we need a state
if r.state == nil {
r.state = &terraform.InstanceState{}
}
oldStateVal, err := hcl2shim.HCL2ValueFromFlatmap(r.state.Attributes, r.CoreConfigSchema().ImpliedType())
if err != nil {
return err
}
newStateVal = normalizeNullValues(newStateVal, oldStateVal, false)
newStateVal = copyTimeoutValues(newStateVal, oldStateVal)
meta, err := json.Marshal(r.state.Meta)
if err != nil {
return err
}
rio := providers.ImportedResource{
TypeName: r.resourceType,
Private: meta,
State: newStateVal,
}.AsInstanceObject()
r.resourceInstanceObject = rio
return nil
}
// refreshWithoutUpgrade reads the instance state, but does not call
// MigrateState or the StateUpgraders, since those are now invoked in a
// separate API call.
// RefreshWithoutUpgrade is part of the new plugin shims.
//
// Copied from TF directly as we need the schema.ResourceData to generate
// the HCL for now and with this we can get it
func (r *resource) refreshWithoutUpgrade(s *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, *schema.ResourceData, error) {
logger := log.Get()
// If there is no InstanceState means that it's not importable but we have to
// read it to put it on the config
if s != nil {
// If the ID is already somehow blank, it doesn't exist
if s.ID == "" {
return nil, nil, nil
}
rt := schema.ResourceTimeout{}
if _, ok := s.Meta[schema.TimeoutKey]; ok {
if err := rt.StateDecode(s); err != nil {
logger.Log("func", "refreshWithoutUpgrade", "resource", r.Type(), "msg", fmt.Sprintf("[ERR] Error decoding ResourceTimeout: %s", err))
}
}
if r.TFResource().Exists != nil {
// Make a copy of data so that if it is modified it doesn't
// affect our Read later.
data, err := schema.InternalMap(r.TFResource().Schema).Data(s, nil)
if err != nil {
return nil, nil, err
}
exists, err := r.TFResource().Exists(data, meta)
if err != nil {
return nil, nil, err
}
if !exists {
return nil, nil, nil
}
}
}
data, err := schema.InternalMap(r.TFResource().Schema).Data(s, nil)
if err != nil {
return nil, nil, err
}
// If the resouorce it's not Importer then the state it's not important
// and we can use the already created Data.
// This may only happen when the Read requires something that it's not
// and ID
if r.Data() != nil && r.tfResource.Importer == nil {
data = r.Data()
}
// If it has no ID on the data but yes on the resource set it
// this happens in resources which are not Imported (data will be nil)
// and the ID was setted only to the Resource on the initialization of
// the provider
if (data == nil || data.Id() == "") && r.ID() != "" {
data = r.Data()
data.SetId(r.ID())
}
err = r.TFResource().Read(data, meta)
if err != nil {
return nil, nil, err
}
state := data.State()
if state != nil && state.ID == "" {
state = nil
}
if state != nil && r.TFResource().SchemaVersion > 0 {
if state.Meta == nil {
state.Meta = make(map[string]interface{})
}
state.Meta["schema_version"] = strconv.Itoa(r.TFResource().SchemaVersion)
}
return state, data, nil
}
// State calculates the state of the Resource and
// writes it to w
func (r *resource) State(w writer.Writer) error {
if importer := r.tfResource.Importer; importer != nil {
// If it does not have any configName we will generate one
// and store it, so net time it'll use that one on any config
if r.configName == "" {
configName := tag.GetNameFromTag(r.provider.TagKey(), r.data, r.id)
if ok, err := w.Has(configName); err != nil {
return err
} else if ok {
configName = pwgen.Alpha(5)
}
err := w.Write(fmt.Sprintf("%s.%s", r.resourceType, configName), r)
if err != nil {
return err
}
r.configName = configName
} else {
err := w.Write(fmt.Sprintf("%s.%s", r.resourceType, r.configName), r)
if err != nil {
return err
}
return nil
}
}
return nil
}
// HCL returns the HCL configuration of the Resource and
// writes it to HCL
func (r *resource) HCL(w writer.Writer) error {
cfg := mergeFullConfig(r.data, r.tfResource.Schema, "")
// If it does not have any configName we will generate one
// and store it, so net time it'll use that one on any config
if r.configName == "" {
configName := fmt.Sprintf("%s.%s", r.resourceType, tag.GetNameFromTag(r.provider.TagKey(), r.data, r.id))
if ok, err := w.Has(configName); err != nil {
return err
} else if ok {
configName = pwgen.Alpha(5)
}
err := w.Write(fmt.Sprintf("%s.%s", r.resourceType, configName), cfg)
if err != nil {
return err
}
r.configName = configName
} else {
err := w.Write(fmt.Sprintf("%s.%s", r.resourceType, r.configName), cfg)
if err != nil {
return err
}
}
return nil
}
func (r *resource) InstanceInfo() *terraform.InstanceInfo {
return &terraform.InstanceInfo{
Id: r.id,
Type: r.resourceType,
}
}
func (r *resource) CoreConfigSchema() *configschema.Block {
return r.tfResource.CoreConfigSchema()
}
func (r *resource) ResourceInstanceObject() *states.ResourceInstanceObject {
return r.resourceInstanceObject
}
// mergeFullConfig creates the key to the map and if it had a value before set it, if
func mergeFullConfig(cfgr *schema.ResourceData, sch map[string]*schema.Schema, key string) map[string]interface{} {
res := make(map[string]interface{})
// conflicts has all the possible conflicts that we can have at this level
// of the schema, so we do not add a conflicted attribute after the other.
// The structure is:
// * key: Value that is Conflicted with
// * value: Attribute that has Clonflicts
conflicts := make(map[string]string)
for k, v := range sch {
// If it's just a Computed value, do not add it to the output
if !isConfig(v) {
continue
}
// Basically calculates the needed
// key to the current access
var kk string
if key != "" {
kk = key + "." + k
} else {
kk = k
}
// schema.Resource means that it has nested fields
if sr, ok := v.Elem.(*schema.Resource); ok {
// Example would be aws_security_group
if v.Type == schema.TypeSet {
s, ok := cfgr.GetOk(kk)
if !ok {
continue
}
res[k] = normalizeSetList(sr.Schema, s.(*schema.Set).List())
} else if v.Type == schema.TypeList {
var ar interface{} = make([]interface{}, 0)
l, ok := cfgr.GetOk(kk)
if !ok {
continue
}
list := l.([]interface{})
for i := range list {
fc := mergeFullConfig(cfgr, sr.Schema, fmt.Sprintf("%s.%d", kk, i))
// It can be possible that there are no actual values insight, so to not add
// an empty entity we validate it
if len(fc) > 0 {
ar = append(ar.([]interface{}), fc)
}
}
// If no element on the ar, then we just
// ignore it to not add empty values
if len(ar.([]interface{})) > 0 {
res[k] = ar
}
} else {
res[k] = mergeFullConfig(cfgr, sr.Schema, kk)
}
// As it's a nested element it does not require any of
// the other code as it's for single value schemas
continue
}
// This sets the single values that we see on the
// end result
vv, ok := cfgr.GetOk(kk)
// If the value is Required we need to add it
// even if it's not sent
if (!ok || vv == nil) && !v.Required {
continue
}
// A value in which this one conflicts has been set before
// so we should no set this one as it'll raise an error of
// `conflicts with *` on Terraform
if hasConflict(res, v.ConflictsWith) {
continue
}
// If any of the attributes added before has
// a conflict with the current key we have to delete
// the old one and use this one
if c, ok := conflicts[k]; ok {
delete(res, c)
}
// If the ConflictsWith has values we store them on the
// conflicts map so none of those attributes is added after
// this one has been added
if len(v.ConflictsWith) != 0 {
for _, c := range v.ConflictsWith {
conflicts[c] = k
}
}
// If it's a type map, we'll prefix the key with '=tc=' to know
// that it's an attribute so we have to keep the '=' when formatting
// the HCL
if v.Type == schema.TypeMap {
k = "=tc=" + k
}
if s, ok := vv.(*schema.Set); ok {
res[k] = s.List()
} else {
res[k] = normalizeInterpolation(normalizeValue(vv))
}
}
return res
}
// hasConflict checks if any of the keys is present on the res
func hasConflict(res map[string]interface{}, keys []string) bool {
for _, key := range keys {
if _, ok := res[key]; ok {
return true
}
}
return false
}
// normalizeValue removes the \n from the value now
func normalizeValue(v interface{}) interface{} {
if s, ok := v.(string); ok {
return strings.Replace(s, "\n", "", -1)
}
return v
}
var iamInternpolationRe = regexp.MustCompile(`(\$\{[^}]+\})`)
// normalizeInterpolation fixes the https://github.com/hashicorp/terraform/issues/18937
// on reading
func normalizeInterpolation(v interface{}) interface{} {
if s, ok := v.(string); ok {
return iamInternpolationRe.ReplaceAllString(s, `$$$1`)
}
return v
}
// normalizeSetList returns the normalization of a schema.Set.List
// it could be a simple list or a embedded structure.
// The sch it's used to also add required values if needed
func normalizeSetList(sch map[string]*schema.Schema, list []interface{}) interface{} {
var ar interface{} = make([]interface{}, 0)
for _, set := range list {
switch val := set.(type) {
case map[string]interface{}:
// This case it's when a TypeSet has
// a nested structure,
// example: aws_security_group.ingress
res := make(map[string]interface{})
for k, v := range val {
switch vv := v.(type) {
case *schema.Set:
nsch := make(map[string]*schema.Schema)
if sc, ok := sch[k]; ok {
if rs, ok := sc.Elem.(*schema.Resource); ok {
nsch = rs.Schema
}
}
ns := normalizeSetList(nsch, vv.List())
if !isDefault(sch[k], ns) {
res[k] = ns
}
case []interface{}:
nsch := make(map[string]*schema.Schema)
if sc, ok := sch[k]; ok {
if rs, ok := sc.Elem.(*schema.Resource); ok {
nsch = rs.Schema
}
}
ns := normalizeSetList(nsch, vv)
if !isDefault(sch[k], ns) {
res[k] = ns
}
case interface{}:
if !isDefault(sch[k], v) {
res[k] = v
}
}
}
ar = append(ar.([]interface{}), res)
case []interface{}:
ns := normalizeSetList(sch, val)
if !isDefault(nil, ns) {
ar = append(ar.([]interface{}), ns)
}
case interface{}:
// This case is normally for the
// "Type: schema.TypeSet, Elm: schema.Schema{Type: schema.TypeString}"
// definitions on TF,
// example: aws_security_group.ingress.security_groups
if !isDefault(nil, val) {
ar = append(ar.([]interface{}), val)
}
}
}
return ar
}
var (
// Ideally this could be generated using "enumer", it
// would be a better idea as then we do not have
// to maintain this list
tfTypes = []schema.ValueType{
schema.TypeBool,
schema.TypeInt,
schema.TypeFloat,
schema.TypeString,
schema.TypeList,
schema.TypeMap,
schema.TypeSet,
}
)
// isDefault is used on normalizSet as the Sets do not use the normal
// TF strucure (access by key) and are stored as raw maps with some
// default values that we don't want on the HCL output.
// example: [], false, "", 0 ...
func isDefault(sch *schema.Schema, v interface{}) bool {
if sch != nil {
if sch.Required {
return false
}
// This way values that are not suppose
// to be on the config are also not added
if !isConfig(sch) {
return true
}
}
for _, t := range tfTypes {
if reflect.DeepEqual(t.Zero(), v) {
// If it has a default value which is different
// than the one v then v has to be setted.
// Example: Default => true, v => false
// the v = false has to be setted
if sch.Default != nil {
if v != sch.Default {
return false
}
}
return true
}
}
return false
}
// isConfig checks if the sch has to be
// set to a config opt or not
func isConfig(sch *schema.Schema) bool {
if (sch.Computed && !sch.Optional && !sch.Required) || sch.Deprecated != "" {
return false
}
return true
}
// COPIED FROM TF AS THOSE ARE PRIVATE BUT NEEDED
// Zero values and empty containers may be interchanged by the apply process.
// When there is a discrepency between src and dst value being null or empty,
// prefer the src value. This takes a little more liberty with set types, since
// we can't correlate modified set values. In the case of sets, if the src set
// was wholly known we assume the value was correctly applied and copy that
// entirely to the new value.
// While apply prefers the src value, during plan we prefer dst whenever there
// is an unknown or a set is involved, since the plan can alter the value
// however it sees fit. This however means that a CustomizeDiffFunction may not
// be able to change a null to an empty value or vice versa, but that should be
// very uncommon nor was it reliable before 0.12 either.
func normalizeNullValues(dst, src cty.Value, apply bool) cty.Value {
ty := dst.Type()
if !src.IsNull() && !src.IsKnown() {
// Return src during plan to retain unknown interpolated placeholders,
// which could be lost if we're only updating a resource. If this is a
// read scenario, then there shouldn't be any unknowns at all.
if dst.IsNull() && !apply {
return src
}
return dst
}
// Handle null/empty changes for collections during apply.
// A change between null and empty values prefers src to make sure the state
// is consistent between plan and apply.
if ty.IsCollectionType() && apply {
dstEmpty := !dst.IsNull() && dst.IsKnown() && dst.LengthInt() == 0
srcEmpty := !src.IsNull() && src.IsKnown() && src.LengthInt() == 0
if (src.IsNull() && dstEmpty) || (srcEmpty && dst.IsNull()) {
return src
}
}
if src.IsNull() || !src.IsKnown() || !dst.IsKnown() {
return dst
}
switch {
case ty.IsMapType(), ty.IsObjectType():
var dstMap map[string]cty.Value
if !dst.IsNull() {
dstMap = dst.AsValueMap()
}
if dstMap == nil {
dstMap = map[string]cty.Value{}
}
srcMap := src.AsValueMap()
for key, v := range srcMap {
dstVal, ok := dstMap[key]
if !ok && apply && ty.IsMapType() {
// don't transfer old map values to dst during apply
continue
}
if dstVal == cty.NilVal {
if !apply && ty.IsMapType() {
// let plan shape this map however it wants
continue
}
dstVal = cty.NullVal(v.Type())
}
dstMap[key] = normalizeNullValues(dstVal, v, apply)
}
// you can't call MapVal/ObjectVal with empty maps, but nothing was
// copied in anyway. If the dst is nil, and the src is known, assume the
// src is correct.
if len(dstMap) == 0 {
if dst.IsNull() && src.IsWhollyKnown() && apply {
return src
}
return dst
}
if ty.IsMapType() {
// helper/schema will populate an optional+computed map with
// unknowns which we have to fixup here.
// It would be preferable to simply prevent any known value from
// becoming unknown, but concessions have to be made to retain the
// broken legacy behavior when possible.
for k, srcVal := range srcMap {
if !srcVal.IsNull() && srcVal.IsKnown() {
dstVal, ok := dstMap[k]
if !ok {
continue
}
if !dstVal.IsNull() && !dstVal.IsKnown() {
dstMap[k] = srcVal
}
}
}
return cty.MapVal(dstMap)
}
return cty.ObjectVal(dstMap)
case ty.IsSetType():
// If the original was wholly known, then we expect that is what the
// provider applied. The apply process loses too much information to
// reliably re-create the set.
if src.IsWhollyKnown() && apply {
return src
}
case ty.IsListType(), ty.IsTupleType():
// If the dst is null, and the src is known, then we lost an empty value
// so take the original.
if dst.IsNull() {
if src.IsWhollyKnown() && src.LengthInt() == 0 && apply {
return src
}
// if dst is null and src only contains unknown values, then we lost
// those during a read or plan.
if !apply && !src.IsNull() {
allUnknown := true
for _, v := range src.AsValueSlice() {
if v.IsKnown() {
allUnknown = false
break
}
}
if allUnknown {
return src
}
}
return dst
}
// if the lengths are identical, then iterate over each element in succession.
srcLen := src.LengthInt()
dstLen := dst.LengthInt()
if srcLen == dstLen && srcLen > 0 {
srcs := src.AsValueSlice()
dsts := dst.AsValueSlice()
for i := 0; i < srcLen; i++ {
dsts[i] = normalizeNullValues(dsts[i], srcs[i], apply)
}
if ty.IsTupleType() {
return cty.TupleVal(dsts)
}
return cty.ListVal(dsts)
}
case ty.IsPrimitiveType():
if dst.IsNull() && src.IsWhollyKnown() && apply {
return src
}
}
return dst
}
// helper/schema throws away timeout values from the config and stores them in
// the Private/Meta fields. we need to copy those values into the planned state
// so that core doesn't see a perpetual diff with the timeout block.
func copyTimeoutValues(to cty.Value, from cty.Value) cty.Value {
// if `to` is null we are planning to remove it altogether.
if to.IsNull() {
return to
}
toAttrs := to.AsValueMap()
// We need to remove the key since the hcl2shims will add a non-null block
// because we can't determine if a single block was null from the flatmapped
// values. This needs to conform to the correct schema for marshaling, so
// change the value to null rather than deleting it from the object map.
timeouts, ok := toAttrs[schema.TimeoutsConfigKey]
if ok {
toAttrs[schema.TimeoutsConfigKey] = cty.NullVal(timeouts.Type())
}
// if from is null then there are no timeouts to copy
if from.IsNull() {
return cty.ObjectVal(toAttrs)
}
fromAttrs := from.AsValueMap()
timeouts, ok = fromAttrs[schema.TimeoutsConfigKey]
// timeouts shouldn't be unknown, but don't copy possibly invalid values either
if !ok || timeouts.IsNull() || !timeouts.IsWhollyKnown() {
// no timeouts block to copy
return cty.ObjectVal(toAttrs)
}
toAttrs[schema.TimeoutsConfigKey] = timeouts
return cty.ObjectVal(toAttrs)
}