-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
diff.go
2076 lines (1840 loc) · 63.5 KB
/
diff.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package format
import (
"bufio"
"bytes"
"fmt"
"log"
"sort"
"strings"
"github.com/mitchellh/colorstring"
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"
"github.com/hashicorp/terraform/internal/addrs"
"github.com/hashicorp/terraform/internal/configs/configschema"
"github.com/hashicorp/terraform/internal/lang/marks"
"github.com/hashicorp/terraform/internal/plans"
"github.com/hashicorp/terraform/internal/plans/objchange"
"github.com/hashicorp/terraform/internal/states"
)
// ResourceChange returns a string representation of a change to a particular
// resource, for inclusion in user-facing plan output.
//
// The resource schema must be provided along with the change so that the
// formatted change can reflect the configuration structure for the associated
// resource.
//
// If "color" is non-nil, it will be used to color the result. Otherwise,
// no color codes will be included.
func ResourceChange(
change *plans.ResourceInstanceChangeSrc,
schema *configschema.Block,
color *colorstring.Colorize,
) string {
addr := change.Addr
var buf bytes.Buffer
if color == nil {
color = &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Disable: true,
Reset: false,
}
}
dispAddr := addr.String()
if change.DeposedKey != states.NotDeposed {
dispAddr = fmt.Sprintf("%s (deposed object %s)", dispAddr, change.DeposedKey)
}
switch change.Action {
case plans.Create:
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be created", dispAddr)))
case plans.Read:
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be read during apply\n # (config refers to values not yet known)", dispAddr)))
case plans.Update:
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be updated in-place", dispAddr)))
case plans.CreateThenDelete, plans.DeleteThenCreate:
switch change.ActionReason {
case plans.ResourceInstanceReplaceBecauseTainted:
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] is tainted, so must be [bold][red]replaced", dispAddr)))
case plans.ResourceInstanceReplaceByRequest:
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be [bold][red]replaced[reset], as requested", dispAddr)))
default:
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] must be [bold][red]replaced", dispAddr)))
}
case plans.Delete:
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be [bold][red]destroyed", dispAddr)))
if change.DeposedKey != states.NotDeposed {
// Some extra context about this unusual situation.
buf.WriteString(color.Color("\n # (left over from a partially-failed replacement of this instance)"))
}
case plans.NoOp:
if change.Moved() {
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] has moved to [bold]%s[reset]", change.PrevRunAddr.String(), dispAddr)))
break
}
fallthrough
default:
// should never happen, since the above is exhaustive
buf.WriteString(fmt.Sprintf("%s has an action the plan renderer doesn't support (this is a bug)", dispAddr))
}
buf.WriteString(color.Color("[reset]\n"))
if change.Moved() && change.Action != plans.NoOp {
buf.WriteString(color.Color(fmt.Sprintf("[bold] # [reset]([bold]%s[reset] has moved to [bold]%s[reset])\n", change.PrevRunAddr.String(), dispAddr)))
}
if change.Moved() && change.Action == plans.NoOp {
buf.WriteString(" ")
} else {
buf.WriteString(color.Color(DiffActionSymbol(change.Action)) + " ")
}
switch addr.Resource.Resource.Mode {
case addrs.ManagedResourceMode:
buf.WriteString(fmt.Sprintf(
"resource %q %q",
addr.Resource.Resource.Type,
addr.Resource.Resource.Name,
))
case addrs.DataResourceMode:
buf.WriteString(fmt.Sprintf(
"data %q %q ",
addr.Resource.Resource.Type,
addr.Resource.Resource.Name,
))
default:
// should never happen, since the above is exhaustive
buf.WriteString(addr.String())
}
buf.WriteString(" {")
p := blockBodyDiffPrinter{
buf: &buf,
color: color,
action: change.Action,
requiredReplace: change.RequiredReplace,
}
// Most commonly-used resources have nested blocks that result in us
// going at least three traversals deep while we recurse here, so we'll
// start with that much capacity and then grow as needed for deeper
// structures.
path := make(cty.Path, 0, 3)
changeV, err := change.Decode(schema.ImpliedType())
if err != nil {
// Should never happen in here, since we've already been through
// loads of layers of encode/decode of the planned changes before now.
panic(fmt.Sprintf("failed to decode plan for %s while rendering diff: %s", addr, err))
}
// We currently have an opt-out that permits the legacy SDK to return values
// that defy our usual conventions around handling of nesting blocks. To
// avoid the rendering code from needing to handle all of these, we'll
// normalize first.
// (Ideally we'd do this as part of the SDK opt-out implementation in core,
// but we've added it here for now to reduce risk of unexpected impacts
// on other code in core.)
changeV.Change.Before = objchange.NormalizeObjectFromLegacySDK(changeV.Change.Before, schema)
changeV.Change.After = objchange.NormalizeObjectFromLegacySDK(changeV.Change.After, schema)
result := p.writeBlockBodyDiff(schema, changeV.Before, changeV.After, 6, path)
if result.bodyWritten {
buf.WriteString("\n")
buf.WriteString(strings.Repeat(" ", 4))
}
buf.WriteString("}\n")
return buf.String()
}
// ResourceInstanceDrift returns a string representation of a change to a
// particular resource instance that was made outside of Terraform, for
// reporting a change that has already happened rather than one that is planned.
//
// The the two resource instances have equal current objects then the result
// will be an empty string to indicate that there is no drift to render.
//
// The resource schema must be provided along with the change so that the
// formatted change can reflect the configuration structure for the associated
// resource.
//
// If "color" is non-nil, it will be used to color the result. Otherwise,
// no color codes will be included.
func ResourceInstanceDrift(
addr addrs.AbsResourceInstance,
before, after *states.ResourceInstance,
schema *configschema.Block,
color *colorstring.Colorize,
) string {
var buf bytes.Buffer
if color == nil {
color = &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Disable: true,
Reset: false,
}
}
dispAddr := addr.String()
action := plans.Update
switch {
case before == nil || before.Current == nil:
// before should never be nil, but before.Current can be if the
// instance was deposed. There is nothing to render for a deposed
// instance, since we intend to remove it.
return ""
case after == nil || after.Current == nil:
// The object was deleted
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] has been deleted", dispAddr)))
action = plans.Delete
default:
// The object was changed
buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] has been changed", dispAddr)))
}
buf.WriteString(color.Color("[reset]\n"))
buf.WriteString(color.Color(DiffActionSymbol(action)) + " ")
switch addr.Resource.Resource.Mode {
case addrs.ManagedResourceMode:
buf.WriteString(fmt.Sprintf(
"resource %q %q",
addr.Resource.Resource.Type,
addr.Resource.Resource.Name,
))
case addrs.DataResourceMode:
buf.WriteString(fmt.Sprintf(
"data %q %q ",
addr.Resource.Resource.Type,
addr.Resource.Resource.Name,
))
default:
// should never happen, since the above is exhaustive
buf.WriteString(addr.String())
}
buf.WriteString(" {")
p := blockBodyDiffPrinter{
buf: &buf,
color: color,
action: action,
}
// Most commonly-used resources have nested blocks that result in us
// going at least three traversals deep while we recurse here, so we'll
// start with that much capacity and then grow as needed for deeper
// structures.
path := make(cty.Path, 0, 3)
ty := schema.ImpliedType()
var err error
var oldObj, newObj *states.ResourceInstanceObject
oldObj, err = before.Current.Decode(ty)
if err != nil {
// We shouldn't encounter errors here because Terraform Core should've
// made sure that the previous run object conforms to the current
// schema by having the provider upgrade it, but we'll be robust here
// in case there are some edges we didn't find yet.
return fmt.Sprintf(" # %s previous run state doesn't conform to current schema; this is a Terraform bug\n # %s\n", addr, err)
}
if after != nil && after.Current != nil {
newObj, err = after.Current.Decode(ty)
if err != nil {
// We shouldn't encounter errors here because Terraform Core should've
// made sure that the prior state object conforms to the current
// schema by having the provider upgrade it, even if we skipped
// refreshing on this run, but we'll be robust here in case there are
// some edges we didn't find yet.
return fmt.Sprintf(" # %s refreshed state doesn't conform to current schema; this is a Terraform bug\n # %s\n", addr, err)
}
}
oldVal := oldObj.Value
var newVal cty.Value
if newObj != nil {
newVal = newObj.Value
} else {
newVal = cty.NullVal(ty)
}
if newVal.RawEquals(oldVal) {
// Nothing to show, then.
return ""
}
// We currently have an opt-out that permits the legacy SDK to return values
// that defy our usual conventions around handling of nesting blocks. To
// avoid the rendering code from needing to handle all of these, we'll
// normalize first.
// (Ideally we'd do this as part of the SDK opt-out implementation in core,
// but we've added it here for now to reduce risk of unexpected impacts
// on other code in core.)
oldVal = objchange.NormalizeObjectFromLegacySDK(oldVal, schema)
newVal = objchange.NormalizeObjectFromLegacySDK(newVal, schema)
result := p.writeBlockBodyDiff(schema, oldVal, newVal, 6, path)
if result.bodyWritten {
buf.WriteString("\n")
buf.WriteString(strings.Repeat(" ", 4))
}
buf.WriteString("}\n")
return buf.String()
}
// OutputChanges returns a string representation of a set of changes to output
// values for inclusion in user-facing plan output.
//
// If "color" is non-nil, it will be used to color the result. Otherwise,
// no color codes will be included.
func OutputChanges(
changes []*plans.OutputChangeSrc,
color *colorstring.Colorize,
) string {
var buf bytes.Buffer
p := blockBodyDiffPrinter{
buf: &buf,
color: color,
action: plans.Update, // not actually used in this case, because we're not printing a containing block
}
// We're going to reuse the codepath we used for printing resource block
// diffs, by pretending that the set of defined outputs are the attributes
// of some resource. It's a little forced to do this, but it gives us all
// the same formatting heuristics as we normally use for resource
// attributes.
oldVals := make(map[string]cty.Value, len(changes))
newVals := make(map[string]cty.Value, len(changes))
synthSchema := &configschema.Block{
Attributes: make(map[string]*configschema.Attribute, len(changes)),
}
for _, changeSrc := range changes {
name := changeSrc.Addr.OutputValue.Name
change, err := changeSrc.Decode()
if err != nil {
// It'd be weird to get a decoding error here because that would
// suggest that Terraform itself just produced an invalid plan, and
// we don't have any good way to ignore it in this codepath, so
// we'll just log it and ignore it.
log.Printf("[ERROR] format.OutputChanges: Failed to decode planned change for output %q: %s", name, err)
continue
}
synthSchema.Attributes[name] = &configschema.Attribute{
Type: cty.DynamicPseudoType, // output types are decided dynamically based on the given value
Optional: true,
Sensitive: change.Sensitive,
}
oldVals[name] = change.Before
newVals[name] = change.After
}
p.writeBlockBodyDiff(synthSchema, cty.ObjectVal(oldVals), cty.ObjectVal(newVals), 2, nil)
return buf.String()
}
type blockBodyDiffPrinter struct {
buf *bytes.Buffer
color *colorstring.Colorize
action plans.Action
requiredReplace cty.PathSet
// verbose is set to true when using the "diff" printer to format state
verbose bool
}
type blockBodyDiffResult struct {
bodyWritten bool
skippedAttributes int
skippedBlocks int
}
const forcesNewResourceCaption = " [red]# forces replacement[reset]"
// writeBlockBodyDiff writes attribute or block differences
// and returns true if any differences were found and written
func (p *blockBodyDiffPrinter) writeBlockBodyDiff(schema *configschema.Block, old, new cty.Value, indent int, path cty.Path) blockBodyDiffResult {
path = ctyEnsurePathCapacity(path, 1)
result := blockBodyDiffResult{}
// write the attributes diff
blankBeforeBlocks := p.writeAttrsDiff(schema.Attributes, old, new, indent, path, &result)
p.writeSkippedAttr(result.skippedAttributes, indent+2)
{
blockTypeNames := make([]string, 0, len(schema.BlockTypes))
for name := range schema.BlockTypes {
blockTypeNames = append(blockTypeNames, name)
}
sort.Strings(blockTypeNames)
for _, name := range blockTypeNames {
blockS := schema.BlockTypes[name]
oldVal := ctyGetAttrMaybeNull(old, name)
newVal := ctyGetAttrMaybeNull(new, name)
result.bodyWritten = true
skippedBlocks := p.writeNestedBlockDiffs(name, blockS, oldVal, newVal, blankBeforeBlocks, indent, path)
if skippedBlocks > 0 {
result.skippedBlocks += skippedBlocks
}
// Always include a blank for any subsequent block types.
blankBeforeBlocks = true
}
if result.skippedBlocks > 0 {
noun := "blocks"
if result.skippedBlocks == 1 {
noun = "block"
}
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent+2))
p.buf.WriteString(p.color.Color(fmt.Sprintf("[dark_gray]# (%d unchanged %s hidden)[reset]", result.skippedBlocks, noun)))
}
}
return result
}
func (p *blockBodyDiffPrinter) writeAttrsDiff(
attrsS map[string]*configschema.Attribute,
old, new cty.Value,
indent int,
path cty.Path,
result *blockBodyDiffResult) bool {
blankBeforeBlocks := false
attrNames := make([]string, 0, len(attrsS))
attrNameLen := 0
for name := range attrsS {
oldVal := ctyGetAttrMaybeNull(old, name)
newVal := ctyGetAttrMaybeNull(new, name)
if oldVal.IsNull() && newVal.IsNull() {
// Skip attributes where both old and new values are null
// (we do this early here so that we'll do our value alignment
// based on the longest attribute name that has a change, rather
// than the longest attribute name in the full set.)
continue
}
attrNames = append(attrNames, name)
if len(name) > attrNameLen {
attrNameLen = len(name)
}
}
sort.Strings(attrNames)
if len(attrNames) > 0 {
blankBeforeBlocks = true
}
for _, name := range attrNames {
attrS := attrsS[name]
oldVal := ctyGetAttrMaybeNull(old, name)
newVal := ctyGetAttrMaybeNull(new, name)
result.bodyWritten = true
skipped := p.writeAttrDiff(name, attrS, oldVal, newVal, attrNameLen, indent, path)
if skipped {
result.skippedAttributes++
}
}
return blankBeforeBlocks
}
// getPlanActionAndShow returns the action value
// and a boolean for showJustNew. In this function we
// modify the old and new values to remove any possible marks
func getPlanActionAndShow(old cty.Value, new cty.Value) (plans.Action, bool) {
var action plans.Action
showJustNew := false
switch {
case old.IsNull():
action = plans.Create
showJustNew = true
case new.IsNull():
action = plans.Delete
case ctyEqualWithUnknown(old, new):
action = plans.NoOp
showJustNew = true
default:
action = plans.Update
}
return action, showJustNew
}
func (p *blockBodyDiffPrinter) writeAttrDiff(name string, attrS *configschema.Attribute, old, new cty.Value, nameLen, indent int, path cty.Path) bool {
path = append(path, cty.GetAttrStep{Name: name})
action, showJustNew := getPlanActionAndShow(old, new)
if action == plans.NoOp && !p.verbose && !identifyingAttribute(name, attrS) {
return true
}
if attrS.NestedType != nil {
p.writeNestedAttrDiff(name, attrS.NestedType, old, new, nameLen, indent, path, action, showJustNew)
return false
}
p.buf.WriteString("\n")
p.writeSensitivityWarning(old, new, indent, action, false)
p.buf.WriteString(strings.Repeat(" ", indent))
p.writeActionSymbol(action)
p.buf.WriteString(p.color.Color("[bold]"))
p.buf.WriteString(name)
p.buf.WriteString(p.color.Color("[reset]"))
p.buf.WriteString(strings.Repeat(" ", nameLen-len(name)))
p.buf.WriteString(" = ")
if attrS.Sensitive {
p.buf.WriteString("(sensitive value)")
if p.pathForcesNewResource(path) {
p.buf.WriteString(p.color.Color(forcesNewResourceCaption))
}
} else {
switch {
case showJustNew:
p.writeValue(new, action, indent+2)
if p.pathForcesNewResource(path) {
p.buf.WriteString(p.color.Color(forcesNewResourceCaption))
}
default:
// We show new even if it is null to emphasize the fact
// that it is being unset, since otherwise it is easy to
// misunderstand that the value is still set to the old value.
p.writeValueDiff(old, new, indent+2, path)
}
}
return false
}
// writeNestedAttrDiff is responsible for formatting Attributes with NestedTypes
// in the diff.
func (p *blockBodyDiffPrinter) writeNestedAttrDiff(
name string, objS *configschema.Object, old, new cty.Value,
nameLen, indent int, path cty.Path, action plans.Action, showJustNew bool) {
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent))
p.writeActionSymbol(action)
p.buf.WriteString(p.color.Color("[bold]"))
p.buf.WriteString(name)
p.buf.WriteString(p.color.Color("[reset]"))
p.buf.WriteString(strings.Repeat(" ", nameLen-len(name)))
result := &blockBodyDiffResult{}
switch objS.Nesting {
case configschema.NestingSingle:
p.buf.WriteString(" = {")
if action != plans.NoOp && (p.pathForcesNewResource(path) || p.pathForcesNewResource(path[:len(path)-1])) {
p.buf.WriteString(p.color.Color(forcesNewResourceCaption))
}
p.writeAttrsDiff(objS.Attributes, old, new, indent+2, path, result)
p.writeSkippedAttr(result.skippedAttributes, indent+4)
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent))
p.buf.WriteString("}")
case configschema.NestingList:
p.buf.WriteString(" = [")
if action != plans.NoOp && (p.pathForcesNewResource(path) || p.pathForcesNewResource(path[:len(path)-1])) {
p.buf.WriteString(p.color.Color(forcesNewResourceCaption))
}
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent+4))
p.writeActionSymbol(action)
p.buf.WriteString("{")
oldItems := ctyCollectionValues(old)
newItems := ctyCollectionValues(new)
// Here we intentionally preserve the index-based correspondance
// between old and new, rather than trying to detect insertions
// and removals in the list, because this more accurately reflects
// how Terraform Core and providers will understand the change,
// particularly when the nested block contains computed attributes
// that will themselves maintain correspondance by index.
// commonLen is number of elements that exist in both lists, which
// will be presented as updates (~). Any additional items in one
// of the lists will be presented as either creates (+) or deletes (-)
// depending on which list they belong to.
var commonLen int
// unchanged is the number of unchanged elements
var unchanged int
switch {
case len(oldItems) < len(newItems):
commonLen = len(oldItems)
default:
commonLen = len(newItems)
}
for i := 0; i < commonLen; i++ {
path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))})
oldItem := oldItems[i]
newItem := newItems[i]
if oldItem.RawEquals(newItem) {
action = plans.NoOp
unchanged++
}
if action != plans.NoOp {
p.writeAttrsDiff(objS.Attributes, oldItem, newItem, indent+6, path, result)
p.writeSkippedAttr(result.skippedAttributes, indent+8)
p.buf.WriteString("\n")
}
}
for i := commonLen; i < len(oldItems); i++ {
path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))})
oldItem := oldItems[i]
newItem := cty.NullVal(oldItem.Type())
p.writeAttrsDiff(objS.Attributes, oldItem, newItem, indent+6, path, result)
p.buf.WriteString("\n")
}
for i := commonLen; i < len(newItems); i++ {
path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))})
newItem := newItems[i]
oldItem := cty.NullVal(newItem.Type())
p.writeAttrsDiff(objS.Attributes, oldItem, newItem, indent+6, path, result)
p.buf.WriteString("\n")
}
p.buf.WriteString(strings.Repeat(" ", indent+4))
p.buf.WriteString("},\n")
p.writeSkippedElems(unchanged, indent+4)
p.buf.WriteString(strings.Repeat(" ", indent+2))
p.buf.WriteString("]")
if !new.IsKnown() {
p.buf.WriteString(" -> (known after apply)")
}
case configschema.NestingSet:
oldItems := ctyCollectionValues(old)
newItems := ctyCollectionValues(new)
var all cty.Value
if len(oldItems)+len(newItems) > 0 {
allItems := make([]cty.Value, 0, len(oldItems)+len(newItems))
allItems = append(allItems, oldItems...)
allItems = append(allItems, newItems...)
all = cty.SetVal(allItems)
} else {
all = cty.SetValEmpty(old.Type().ElementType())
}
p.buf.WriteString(" = [")
for it := all.ElementIterator(); it.Next(); {
_, val := it.Element()
var action plans.Action
var oldValue, newValue cty.Value
switch {
case !val.IsKnown():
action = plans.Update
newValue = val
case !new.IsKnown():
action = plans.Delete
// the value must have come from the old set
oldValue = val
// Mark the new val as null, but the entire set will be
// displayed as "(unknown after apply)"
newValue = cty.NullVal(val.Type())
case old.IsNull() || !old.HasElement(val).True():
action = plans.Create
oldValue = cty.NullVal(val.Type())
newValue = val
case new.IsNull() || !new.HasElement(val).True():
action = plans.Delete
oldValue = val
newValue = cty.NullVal(val.Type())
default:
action = plans.NoOp
oldValue = val
newValue = val
}
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent+4))
p.writeActionSymbol(action)
p.buf.WriteString("{")
if action != plans.NoOp && (p.pathForcesNewResource(path) || p.pathForcesNewResource(path[:len(path)-1])) {
p.buf.WriteString(p.color.Color(forcesNewResourceCaption))
}
path := append(path, cty.IndexStep{Key: val})
p.writeAttrsDiff(objS.Attributes, oldValue, newValue, indent+6, path, result)
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent+4))
p.buf.WriteString("},")
}
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent+2))
p.buf.WriteString("]")
if !new.IsKnown() {
p.buf.WriteString(" -> (known after apply)")
}
case configschema.NestingMap:
// For the sake of handling nested blocks, we'll treat a null map
// the same as an empty map since the config language doesn't
// distinguish these anyway.
old = ctyNullBlockMapAsEmpty(old)
new = ctyNullBlockMapAsEmpty(new)
oldItems := old.AsValueMap()
newItems := map[string]cty.Value{}
if new.IsKnown() {
newItems = new.AsValueMap()
}
allKeys := make(map[string]bool)
for k := range oldItems {
allKeys[k] = true
}
for k := range newItems {
allKeys[k] = true
}
allKeysOrder := make([]string, 0, len(allKeys))
for k := range allKeys {
allKeysOrder = append(allKeysOrder, k)
}
sort.Strings(allKeysOrder)
p.buf.WriteString(" = {\n")
// unchanged tracks the number of unchanged elements
unchanged := 0
for _, k := range allKeysOrder {
var action plans.Action
oldValue := oldItems[k]
newValue := newItems[k]
switch {
case oldValue == cty.NilVal:
oldValue = cty.NullVal(newValue.Type())
action = plans.Create
case newValue == cty.NilVal:
newValue = cty.NullVal(oldValue.Type())
action = plans.Delete
case !newValue.RawEquals(oldValue):
action = plans.Update
default:
action = plans.NoOp
unchanged++
}
if action != plans.NoOp {
p.buf.WriteString(strings.Repeat(" ", indent+4))
p.writeActionSymbol(action)
fmt.Fprintf(p.buf, "%q = {", k)
if p.pathForcesNewResource(path) || p.pathForcesNewResource(path[:len(path)-1]) {
p.buf.WriteString(p.color.Color(forcesNewResourceCaption))
}
path := append(path, cty.IndexStep{Key: cty.StringVal(k)})
p.writeAttrsDiff(objS.Attributes, oldValue, newValue, indent+6, path, result)
p.writeSkippedAttr(result.skippedAttributes, indent+8)
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent+4))
p.buf.WriteString("},\n")
}
}
p.writeSkippedElems(unchanged, indent+4)
p.buf.WriteString(strings.Repeat(" ", indent+2))
p.buf.WriteString("}")
if !new.IsKnown() {
p.buf.WriteString(" -> (known after apply)")
}
}
}
func (p *blockBodyDiffPrinter) writeNestedBlockDiffs(name string, blockS *configschema.NestedBlock, old, new cty.Value, blankBefore bool, indent int, path cty.Path) int {
skippedBlocks := 0
path = append(path, cty.GetAttrStep{Name: name})
if old.IsNull() && new.IsNull() {
// Nothing to do if both old and new is null
return skippedBlocks
}
// If either the old or the new value is marked,
// Display a special diff because it is irrelevant
// to list all obfuscated attributes as (sensitive)
if old.HasMark(marks.Sensitive) || new.HasMark(marks.Sensitive) {
p.writeSensitiveNestedBlockDiff(name, old, new, indent, blankBefore, path)
return 0
}
// Where old/new are collections representing a nesting mode other than
// NestingSingle, we assume the collection value can never be unknown
// since we always produce the container for the nested objects, even if
// the objects within are computed.
switch blockS.Nesting {
case configschema.NestingSingle, configschema.NestingGroup:
var action plans.Action
eqV := new.Equals(old)
switch {
case old.IsNull():
action = plans.Create
case new.IsNull():
action = plans.Delete
case !new.IsWhollyKnown() || !old.IsWhollyKnown():
// "old" should actually always be known due to our contract
// that old values must never be unknown, but we'll allow it
// anyway to be robust.
action = plans.Update
case !eqV.IsKnown() || !eqV.True():
action = plans.Update
}
if blankBefore {
p.buf.WriteRune('\n')
}
skipped := p.writeNestedBlockDiff(name, nil, &blockS.Block, action, old, new, indent, path)
if skipped {
return 1
}
case configschema.NestingList:
// For the sake of handling nested blocks, we'll treat a null list
// the same as an empty list since the config language doesn't
// distinguish these anyway.
old = ctyNullBlockListAsEmpty(old)
new = ctyNullBlockListAsEmpty(new)
oldItems := ctyCollectionValues(old)
newItems := ctyCollectionValues(new)
// Here we intentionally preserve the index-based correspondance
// between old and new, rather than trying to detect insertions
// and removals in the list, because this more accurately reflects
// how Terraform Core and providers will understand the change,
// particularly when the nested block contains computed attributes
// that will themselves maintain correspondance by index.
// commonLen is number of elements that exist in both lists, which
// will be presented as updates (~). Any additional items in one
// of the lists will be presented as either creates (+) or deletes (-)
// depending on which list they belong to.
var commonLen int
switch {
case len(oldItems) < len(newItems):
commonLen = len(oldItems)
default:
commonLen = len(newItems)
}
if blankBefore && (len(oldItems) > 0 || len(newItems) > 0) {
p.buf.WriteRune('\n')
}
for i := 0; i < commonLen; i++ {
path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))})
oldItem := oldItems[i]
newItem := newItems[i]
action := plans.Update
if oldItem.RawEquals(newItem) {
action = plans.NoOp
}
skipped := p.writeNestedBlockDiff(name, nil, &blockS.Block, action, oldItem, newItem, indent, path)
if skipped {
skippedBlocks++
}
}
for i := commonLen; i < len(oldItems); i++ {
path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))})
oldItem := oldItems[i]
newItem := cty.NullVal(oldItem.Type())
skipped := p.writeNestedBlockDiff(name, nil, &blockS.Block, plans.Delete, oldItem, newItem, indent, path)
if skipped {
skippedBlocks++
}
}
for i := commonLen; i < len(newItems); i++ {
path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))})
newItem := newItems[i]
oldItem := cty.NullVal(newItem.Type())
skipped := p.writeNestedBlockDiff(name, nil, &blockS.Block, plans.Create, oldItem, newItem, indent, path)
if skipped {
skippedBlocks++
}
}
case configschema.NestingSet:
// For the sake of handling nested blocks, we'll treat a null set
// the same as an empty set since the config language doesn't
// distinguish these anyway.
old = ctyNullBlockSetAsEmpty(old)
new = ctyNullBlockSetAsEmpty(new)
oldItems := ctyCollectionValues(old)
newItems := ctyCollectionValues(new)
if (len(oldItems) + len(newItems)) == 0 {
// Nothing to do if both sets are empty
return 0
}
allItems := make([]cty.Value, 0, len(oldItems)+len(newItems))
allItems = append(allItems, oldItems...)
allItems = append(allItems, newItems...)
all := cty.SetVal(allItems)
if blankBefore {
p.buf.WriteRune('\n')
}
for it := all.ElementIterator(); it.Next(); {
_, val := it.Element()
var action plans.Action
var oldValue, newValue cty.Value
switch {
case !val.IsKnown():
action = plans.Update
newValue = val
case !old.HasElement(val).True():
action = plans.Create
oldValue = cty.NullVal(val.Type())
newValue = val
case !new.HasElement(val).True():
action = plans.Delete
oldValue = val
newValue = cty.NullVal(val.Type())
default:
action = plans.NoOp
oldValue = val
newValue = val
}
path := append(path, cty.IndexStep{Key: val})
skipped := p.writeNestedBlockDiff(name, nil, &blockS.Block, action, oldValue, newValue, indent, path)
if skipped {
skippedBlocks++
}
}
case configschema.NestingMap:
// For the sake of handling nested blocks, we'll treat a null map
// the same as an empty map since the config language doesn't
// distinguish these anyway.
old = ctyNullBlockMapAsEmpty(old)
new = ctyNullBlockMapAsEmpty(new)
oldItems := old.AsValueMap()
newItems := new.AsValueMap()
if (len(oldItems) + len(newItems)) == 0 {
// Nothing to do if both maps are empty
return 0
}
allKeys := make(map[string]bool)
for k := range oldItems {
allKeys[k] = true
}
for k := range newItems {
allKeys[k] = true
}
allKeysOrder := make([]string, 0, len(allKeys))
for k := range allKeys {
allKeysOrder = append(allKeysOrder, k)
}
sort.Strings(allKeysOrder)
if blankBefore {
p.buf.WriteRune('\n')
}
for _, k := range allKeysOrder {
var action plans.Action
oldValue := oldItems[k]
newValue := newItems[k]
switch {
case oldValue == cty.NilVal:
oldValue = cty.NullVal(newValue.Type())
action = plans.Create
case newValue == cty.NilVal:
newValue = cty.NullVal(oldValue.Type())
action = plans.Delete
case !newValue.RawEquals(oldValue):
action = plans.Update
default:
action = plans.NoOp
}
path := append(path, cty.IndexStep{Key: cty.StringVal(k)})
skipped := p.writeNestedBlockDiff(name, &k, &blockS.Block, action, oldValue, newValue, indent, path)
if skipped {
skippedBlocks++
}
}
}
return skippedBlocks
}
func (p *blockBodyDiffPrinter) writeSensitiveNestedBlockDiff(name string, old, new cty.Value, indent int, blankBefore bool, path cty.Path) {
var action plans.Action
switch {
case old.IsNull():
action = plans.Create
case new.IsNull():
action = plans.Delete