/
context_plan2_test.go
3750 lines (3406 loc) · 119 KB
/
context_plan2_test.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 terraform
import (
"bytes"
"errors"
"fmt"
"strings"
"sync"
"testing"
"github.com/davecgh/go-spew/spew"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform/internal/addrs"
"github.com/hashicorp/terraform/internal/checks"
"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/providers"
"github.com/hashicorp/terraform/internal/states"
"github.com/hashicorp/terraform/internal/tfdiags"
"github.com/zclconf/go-cty/cty"
)
func TestContext2Plan_removedDuringRefresh(t *testing.T) {
// This tests the situation where an object tracked in the previous run
// state has been deleted outside of Terraform, which we should detect
// during the refresh step and thus ultimately produce a plan to recreate
// the object, since it's still present in the configuration.
m := testModuleInline(t, map[string]string{
"main.tf": `
resource "test_object" "a" {
}
`,
})
p := simpleMockProvider()
p.GetProviderSchemaResponse = &providers.GetProviderSchemaResponse{
Provider: providers.Schema{Block: simpleTestSchema()},
ResourceTypes: map[string]providers.Schema{
"test_object": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"arg": {Type: cty.String, Optional: true},
},
},
},
},
}
p.ReadResourceFn = func(req providers.ReadResourceRequest) (resp providers.ReadResourceResponse) {
resp.NewState = cty.NullVal(req.PriorState.Type())
return resp
}
p.UpgradeResourceStateFn = func(req providers.UpgradeResourceStateRequest) (resp providers.UpgradeResourceStateResponse) {
// We should've been given the prior state JSON as our input to upgrade.
if !bytes.Contains(req.RawStateJSON, []byte("previous_run")) {
t.Fatalf("UpgradeResourceState request doesn't contain the previous run object\n%s", req.RawStateJSON)
}
// We'll put something different in "arg" as part of upgrading, just
// so that we can verify below that PrevRunState contains the upgraded
// (but NOT refreshed) version of the object.
resp.UpgradedState = cty.ObjectVal(map[string]cty.Value{
"arg": cty.StringVal("upgraded"),
})
return resp
}
addr := mustResourceInstanceAddr("test_object.a")
state := states.BuildState(func(s *states.SyncState) {
s.SetResourceInstanceCurrent(addr, &states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"arg":"previous_run"}`),
Status: states.ObjectTainted,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`))
})
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
plan, diags := ctx.Plan(m, state, DefaultPlanOpts)
assertNoErrors(t, diags)
if !p.UpgradeResourceStateCalled {
t.Errorf("Provider's UpgradeResourceState wasn't called; should've been")
}
if !p.ReadResourceCalled {
t.Errorf("Provider's ReadResource wasn't called; should've been")
}
// The object should be absent from the plan's prior state, because that
// records the result of refreshing.
if got := plan.PriorState.ResourceInstance(addr); got != nil {
t.Errorf(
"instance %s is in the prior state after planning; should've been removed\n%s",
addr, spew.Sdump(got),
)
}
// However, the object should still be in the PrevRunState, because
// that reflects what we believed to exist before refreshing.
if got := plan.PrevRunState.ResourceInstance(addr); got == nil {
t.Errorf(
"instance %s is missing from the previous run state after planning; should've been preserved",
addr,
)
} else {
if !bytes.Contains(got.Current.AttrsJSON, []byte("upgraded")) {
t.Fatalf("previous run state has non-upgraded object\n%s", got.Current.AttrsJSON)
}
}
// This situation should result in a drifted resource change.
var drifted *plans.ResourceInstanceChangeSrc
for _, dr := range plan.DriftedResources {
if dr.Addr.Equal(addr) {
drifted = dr
break
}
}
if drifted == nil {
t.Errorf("instance %s is missing from the drifted resource changes", addr)
} else {
if got, want := drifted.Action, plans.Delete; got != want {
t.Errorf("unexpected instance %s drifted resource change action. got: %s, want: %s", addr, got, want)
}
}
// Because the configuration still mentions test_object.a, we should've
// planned to recreate it in order to fix the drift.
for _, c := range plan.Changes.Resources {
if c.Action != plans.Create {
t.Fatalf("expected Create action for missing %s, got %s", c.Addr, c.Action)
}
}
}
func TestContext2Plan_noChangeDataSourceSensitiveNestedSet(t *testing.T) {
m := testModuleInline(t, map[string]string{
"main.tf": `
variable "bar" {
sensitive = true
default = "baz"
}
data "test_data_source" "foo" {
foo {
bar = var.bar
}
}
`,
})
p := new(MockProvider)
p.GetProviderSchemaResponse = getProviderSchemaResponseFromProviderSchema(&ProviderSchema{
DataSources: map[string]*configschema.Block{
"test_data_source": {
Attributes: map[string]*configschema.Attribute{
"id": {
Type: cty.String,
Computed: true,
},
},
BlockTypes: map[string]*configschema.NestedBlock{
"foo": {
Block: configschema.Block{
Attributes: map[string]*configschema.Attribute{
"bar": {Type: cty.String, Optional: true},
},
},
Nesting: configschema.NestingSet,
},
},
},
},
})
p.ReadDataSourceResponse = &providers.ReadDataSourceResponse{
State: cty.ObjectVal(map[string]cty.Value{
"id": cty.StringVal("data_id"),
"foo": cty.SetVal([]cty.Value{cty.ObjectVal(map[string]cty.Value{"bar": cty.StringVal("baz")})}),
}),
}
state := states.NewState()
root := state.EnsureModule(addrs.RootModuleInstance)
root.SetResourceInstanceCurrent(
mustResourceInstanceAddr("data.test_data_source.foo").Resource,
&states.ResourceInstanceObjectSrc{
Status: states.ObjectReady,
AttrsJSON: []byte(`{"id":"data_id", "foo":[{"bar":"baz"}]}`),
AttrSensitivePaths: []cty.PathValueMarks{
{
Path: cty.GetAttrPath("foo"),
Marks: cty.NewValueMarks(marks.Sensitive),
},
},
},
mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`),
)
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
plan, diags := ctx.Plan(m, state, SimplePlanOpts(plans.NormalMode, testInputValuesUnset(m.Module.Variables)))
assertNoErrors(t, diags)
for _, res := range plan.Changes.Resources {
if res.Action != plans.NoOp {
t.Fatalf("expected NoOp, got: %q %s", res.Addr, res.Action)
}
}
}
func TestContext2Plan_orphanDataInstance(t *testing.T) {
// ensure the planned replacement of the data source is evaluated properly
m := testModuleInline(t, map[string]string{
"main.tf": `
data "test_object" "a" {
for_each = { new = "ok" }
}
output "out" {
value = [ for k, _ in data.test_object.a: k ]
}
`,
})
p := simpleMockProvider()
p.ReadDataSourceFn = func(req providers.ReadDataSourceRequest) (resp providers.ReadDataSourceResponse) {
resp.State = req.Config
return resp
}
state := states.BuildState(func(s *states.SyncState) {
s.SetResourceInstanceCurrent(mustResourceInstanceAddr(`data.test_object.a["old"]`), &states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"test_string":"foo"}`),
Status: states.ObjectReady,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`))
})
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
plan, diags := ctx.Plan(m, state, DefaultPlanOpts)
assertNoErrors(t, diags)
change, err := plan.Changes.Outputs[0].Decode()
if err != nil {
t.Fatal(err)
}
expected := cty.TupleVal([]cty.Value{cty.StringVal("new")})
if change.After.Equals(expected).False() {
t.Fatalf("expected %#v, got %#v\n", expected, change.After)
}
}
func TestContext2Plan_basicConfigurationAliases(t *testing.T) {
m := testModuleInline(t, map[string]string{
"main.tf": `
provider "test" {
alias = "z"
test_string = "config"
}
module "mod" {
source = "./mod"
providers = {
test.x = test.z
}
}
`,
"mod/main.tf": `
terraform {
required_providers {
test = {
source = "registry.terraform.io/hashicorp/test"
configuration_aliases = [ test.x ]
}
}
}
resource "test_object" "a" {
provider = test.x
}
`,
})
p := simpleMockProvider()
// The resource within the module should be using the provider configured
// from the root module. We should never see an empty configuration.
p.ConfigureProviderFn = func(req providers.ConfigureProviderRequest) (resp providers.ConfigureProviderResponse) {
if req.Config.GetAttr("test_string").IsNull() {
resp.Diagnostics = resp.Diagnostics.Append(errors.New("missing test_string value"))
}
return resp
}
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
_, diags := ctx.Plan(m, states.NewState(), DefaultPlanOpts)
assertNoErrors(t, diags)
}
func TestContext2Plan_dataReferencesResourceInModules(t *testing.T) {
p := testProvider("test")
p.ReadDataSourceFn = func(req providers.ReadDataSourceRequest) (resp providers.ReadDataSourceResponse) {
cfg := req.Config.AsValueMap()
cfg["id"] = cty.StringVal("d")
resp.State = cty.ObjectVal(cfg)
return resp
}
m := testModuleInline(t, map[string]string{
"main.tf": `
locals {
things = {
old = "first"
new = "second"
}
}
module "mod" {
source = "./mod"
for_each = local.things
}
`,
"./mod/main.tf": `
resource "test_resource" "a" {
}
data "test_data_source" "d" {
depends_on = [test_resource.a]
}
resource "test_resource" "b" {
value = data.test_data_source.d.id
}
`})
oldDataAddr := mustResourceInstanceAddr(`module.mod["old"].data.test_data_source.d`)
state := states.BuildState(func(s *states.SyncState) {
s.SetResourceInstanceCurrent(
mustResourceInstanceAddr(`module.mod["old"].test_resource.a`),
&states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"id":"a"}`),
Status: states.ObjectReady,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`),
)
s.SetResourceInstanceCurrent(
mustResourceInstanceAddr(`module.mod["old"].test_resource.b`),
&states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"id":"b","value":"d"}`),
Status: states.ObjectReady,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`),
)
s.SetResourceInstanceCurrent(
oldDataAddr,
&states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"id":"d"}`),
Status: states.ObjectReady,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`),
)
})
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
plan, diags := ctx.Plan(m, state, DefaultPlanOpts)
assertNoErrors(t, diags)
oldMod := oldDataAddr.Module
for _, c := range plan.Changes.Resources {
// there should be no changes from the old module instance
if c.Addr.Module.Equal(oldMod) && c.Action != plans.NoOp {
t.Errorf("unexpected change %s for %s\n", c.Action, c.Addr)
}
}
}
func TestContext2Plan_resourceChecksInExpandedModule(t *testing.T) {
// When a resource is in a nested module we have two levels of expansion
// to do: first expand the module the resource is declared in, and then
// expand the resource itself.
//
// In earlier versions of Terraform we did that expansion as two levels
// of DynamicExpand, which led to a bug where we didn't have any central
// location from which to register all of the instances of a checkable
// resource.
//
// We now handle the full expansion all in one graph node and one dynamic
// subgraph, which avoids the problem. This is a regression test for the
// earlier bug. If this test is panicking with "duplicate checkable objects
// report" then that suggests the bug is reintroduced and we're now back
// to reporting each module instance separately again, which is incorrect.
p := testProvider("test")
p.GetProviderSchemaResponse = &providers.GetProviderSchemaResponse{
Provider: providers.Schema{
Block: &configschema.Block{},
},
ResourceTypes: map[string]providers.Schema{
"test": {
Block: &configschema.Block{},
},
},
}
p.ReadResourceFn = func(req providers.ReadResourceRequest) (resp providers.ReadResourceResponse) {
resp.NewState = req.PriorState
return resp
}
p.PlanResourceChangeFn = func(req providers.PlanResourceChangeRequest) (resp providers.PlanResourceChangeResponse) {
resp.PlannedState = cty.EmptyObjectVal
return resp
}
p.ApplyResourceChangeFn = func(req providers.ApplyResourceChangeRequest) (resp providers.ApplyResourceChangeResponse) {
resp.NewState = req.PlannedState
return resp
}
m := testModuleInline(t, map[string]string{
"main.tf": `
module "child" {
source = "./child"
count = 2 # must be at least 2 for this test to be valid
}
`,
"child/child.tf": `
locals {
a = "a"
}
resource "test" "test1" {
lifecycle {
postcondition {
# It doesn't matter what this checks as long as it
# passes, because if we don't handle expansion properly
# then we'll crash before we even get to evaluating this.
condition = local.a == local.a
error_message = "Postcondition failed."
}
}
}
resource "test" "test2" {
count = 2
lifecycle {
postcondition {
# It doesn't matter what this checks as long as it
# passes, because if we don't handle expansion properly
# then we'll crash before we even get to evaluating this.
condition = local.a == local.a
error_message = "Postcondition failed."
}
}
}
`,
})
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
priorState := states.NewState()
plan, diags := ctx.Plan(m, priorState, DefaultPlanOpts)
assertNoErrors(t, diags)
resourceInsts := []addrs.AbsResourceInstance{
mustResourceInstanceAddr("module.child[0].test.test1"),
mustResourceInstanceAddr("module.child[0].test.test2[0]"),
mustResourceInstanceAddr("module.child[0].test.test2[1]"),
mustResourceInstanceAddr("module.child[1].test.test1"),
mustResourceInstanceAddr("module.child[1].test.test2[0]"),
mustResourceInstanceAddr("module.child[1].test.test2[1]"),
}
for _, instAddr := range resourceInsts {
t.Run(fmt.Sprintf("results for %s", instAddr), func(t *testing.T) {
if rc := plan.Changes.ResourceInstance(instAddr); rc != nil {
if got, want := rc.Action, plans.Create; got != want {
t.Errorf("wrong action for %s\ngot: %s\nwant: %s", instAddr, got, want)
}
if got, want := rc.ActionReason, plans.ResourceInstanceChangeNoReason; got != want {
t.Errorf("wrong action reason for %s\ngot: %s\nwant: %s", instAddr, got, want)
}
} else {
t.Errorf("no planned change for %s", instAddr)
}
if checkResult := plan.Checks.GetObjectResult(instAddr); checkResult != nil {
if got, want := checkResult.Status, checks.StatusPass; got != want {
t.Errorf("wrong check status for %s\ngot: %s\nwant: %s", instAddr, got, want)
}
} else {
t.Errorf("no check result for %s", instAddr)
}
})
}
}
func TestContext2Plan_dataResourceChecksManagedResourceChange(t *testing.T) {
// This tests the situation where the remote system contains data that
// isn't valid per a data resource postcondition, but that the
// configuration is destined to make the remote system valid during apply
// and so we must defer reading the data resource and checking its
// conditions until the apply step.
//
// This is an exception to the rule tested in
// TestContext2Plan_dataReferencesResourceIndirectly which is relevant
// whenever there's at least one precondition or postcondition attached
// to a data resource.
//
// See TestContext2Plan_managedResourceChecksOtherManagedResourceChange for
// an incorrect situation where a data resource is used only indirectly
// to drive a precondition elsewhere, which therefore doesn't achieve this
// special exception.
p := testProvider("test")
p.GetProviderSchemaResponse = &providers.GetProviderSchemaResponse{
Provider: providers.Schema{
Block: &configschema.Block{},
},
ResourceTypes: map[string]providers.Schema{
"test_resource": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"id": {
Type: cty.String,
Computed: true,
},
"valid": {
Type: cty.Bool,
Required: true,
},
},
},
},
},
DataSources: map[string]providers.Schema{
"test_data_source": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"id": {
Type: cty.String,
Required: true,
},
"valid": {
Type: cty.Bool,
Computed: true,
},
},
},
},
},
}
var mu sync.Mutex
validVal := cty.False
p.ReadResourceFn = func(req providers.ReadResourceRequest) (resp providers.ReadResourceResponse) {
// NOTE: This assumes that the prior state declared below will have
// "valid" set to false already, and thus will match validVal above.
resp.NewState = req.PriorState
return resp
}
p.ReadDataSourceFn = func(req providers.ReadDataSourceRequest) (resp providers.ReadDataSourceResponse) {
cfg := req.Config.AsValueMap()
mu.Lock()
cfg["valid"] = validVal
mu.Unlock()
resp.State = cty.ObjectVal(cfg)
return resp
}
p.PlanResourceChangeFn = func(req providers.PlanResourceChangeRequest) (resp providers.PlanResourceChangeResponse) {
cfg := req.Config.AsValueMap()
prior := req.PriorState.AsValueMap()
resp.PlannedState = cty.ObjectVal(map[string]cty.Value{
"id": prior["id"],
"valid": cfg["valid"],
})
return resp
}
p.ApplyResourceChangeFn = func(req providers.ApplyResourceChangeRequest) (resp providers.ApplyResourceChangeResponse) {
planned := req.PlannedState.AsValueMap()
mu.Lock()
validVal = planned["valid"]
mu.Unlock()
resp.NewState = req.PlannedState
return resp
}
m := testModuleInline(t, map[string]string{
"main.tf": `
resource "test_resource" "a" {
valid = true
}
locals {
# NOTE: We intentionally read through a local value here to make sure
# that this behavior still works even if there isn't a direct dependency
# between the data resource and the managed resource.
object_id = test_resource.a.id
}
data "test_data_source" "a" {
id = local.object_id
lifecycle {
postcondition {
condition = self.valid
error_message = "Not valid!"
}
}
}
`})
managedAddr := mustResourceInstanceAddr(`test_resource.a`)
dataAddr := mustResourceInstanceAddr(`data.test_data_source.a`)
// This state is intended to represent the outcome of a previous apply that
// failed due to postcondition failure but had already updated the
// relevant object to be invalid.
//
// It could also potentially represent a similar situation where the
// previous apply succeeded but there has been a change outside of
// Terraform that made it invalid, although technically in that scenario
// the state data would become invalid only during the planning step. For
// our purposes here that's close enough because we don't have a real
// remote system in place anyway.
priorState := states.BuildState(func(s *states.SyncState) {
s.SetResourceInstanceCurrent(
managedAddr,
&states.ResourceInstanceObjectSrc{
// NOTE: "valid" is false here but is true in the configuration
// above, which is intended to represent that applying the
// configuration change would make this object become valid.
AttrsJSON: []byte(`{"id":"boop","valid":false}`),
Status: states.ObjectReady,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`),
)
})
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
plan, diags := ctx.Plan(m, priorState, DefaultPlanOpts)
assertNoErrors(t, diags)
if rc := plan.Changes.ResourceInstance(dataAddr); rc != nil {
if got, want := rc.Action, plans.Read; got != want {
t.Errorf("wrong action for %s\ngot: %s\nwant: %s", dataAddr, got, want)
}
if got, want := rc.ActionReason, plans.ResourceInstanceReadBecauseDependencyPending; got != want {
t.Errorf("wrong action reason for %s\ngot: %s\nwant: %s", dataAddr, got, want)
}
} else {
t.Fatalf("no planned change for %s", dataAddr)
}
if rc := plan.Changes.ResourceInstance(managedAddr); rc != nil {
if got, want := rc.Action, plans.Update; got != want {
t.Errorf("wrong action for %s\ngot: %s\nwant: %s", managedAddr, got, want)
}
if got, want := rc.ActionReason, plans.ResourceInstanceChangeNoReason; got != want {
t.Errorf("wrong action reason for %s\ngot: %s\nwant: %s", managedAddr, got, want)
}
} else {
t.Fatalf("no planned change for %s", managedAddr)
}
// This is primarily a plan-time test, since the special handling of
// data resources is a plan-time concern, but we'll still try applying the
// plan here just to make sure it's valid.
newState, diags := ctx.Apply(plan, m)
assertNoErrors(t, diags)
if rs := newState.ResourceInstance(dataAddr); rs != nil {
if !rs.HasCurrent() {
t.Errorf("no final state for %s", dataAddr)
}
} else {
t.Errorf("no final state for %s", dataAddr)
}
if rs := newState.ResourceInstance(managedAddr); rs != nil {
if !rs.HasCurrent() {
t.Errorf("no final state for %s", managedAddr)
}
} else {
t.Errorf("no final state for %s", managedAddr)
}
if got, want := validVal, cty.True; got != want {
t.Errorf("wrong final valid value\ngot: %#v\nwant: %#v", got, want)
}
}
func TestContext2Plan_managedResourceChecksOtherManagedResourceChange(t *testing.T) {
// This tests the incorrect situation where a managed resource checks
// another managed resource indirectly via a data resource.
// This doesn't work because Terraform can't tell that the data resource
// outcome will be updated by a separate managed resource change and so
// we expect it to fail.
// This would ideally have worked except that we previously included a
// special case in the rules for data resources where they only consider
// direct dependencies when deciding whether to defer (except when the
// data resource itself has conditions) and so they can potentially
// read "too early" if the user creates the explicitly-not-recommended
// situation of a data resource and a managed resource in the same
// configuration both representing the same remote object.
p := testProvider("test")
p.GetProviderSchemaResponse = &providers.GetProviderSchemaResponse{
Provider: providers.Schema{
Block: &configschema.Block{},
},
ResourceTypes: map[string]providers.Schema{
"test_resource": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"id": {
Type: cty.String,
Computed: true,
},
"valid": {
Type: cty.Bool,
Required: true,
},
},
},
},
},
DataSources: map[string]providers.Schema{
"test_data_source": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"id": {
Type: cty.String,
Required: true,
},
"valid": {
Type: cty.Bool,
Computed: true,
},
},
},
},
},
}
var mu sync.Mutex
validVal := cty.False
p.ReadResourceFn = func(req providers.ReadResourceRequest) (resp providers.ReadResourceResponse) {
// NOTE: This assumes that the prior state declared below will have
// "valid" set to false already, and thus will match validVal above.
resp.NewState = req.PriorState
return resp
}
p.ReadDataSourceFn = func(req providers.ReadDataSourceRequest) (resp providers.ReadDataSourceResponse) {
cfg := req.Config.AsValueMap()
if cfg["id"].AsString() == "main" {
mu.Lock()
cfg["valid"] = validVal
mu.Unlock()
}
resp.State = cty.ObjectVal(cfg)
return resp
}
p.PlanResourceChangeFn = func(req providers.PlanResourceChangeRequest) (resp providers.PlanResourceChangeResponse) {
cfg := req.Config.AsValueMap()
prior := req.PriorState.AsValueMap()
resp.PlannedState = cty.ObjectVal(map[string]cty.Value{
"id": prior["id"],
"valid": cfg["valid"],
})
return resp
}
p.ApplyResourceChangeFn = func(req providers.ApplyResourceChangeRequest) (resp providers.ApplyResourceChangeResponse) {
planned := req.PlannedState.AsValueMap()
if planned["id"].AsString() == "main" {
mu.Lock()
validVal = planned["valid"]
mu.Unlock()
}
resp.NewState = req.PlannedState
return resp
}
m := testModuleInline(t, map[string]string{
"main.tf": `
resource "test_resource" "a" {
valid = true
}
locals {
# NOTE: We intentionally read through a local value here because a
# direct reference from data.test_data_source.a to test_resource.a would
# cause Terraform to defer the data resource to the apply phase due to
# there being a pending change for the managed resource. We're explicitly
# testing the failure case where the data resource read happens too
# eagerly, which is what results from the reference being only indirect
# so Terraform can't "see" that the data resource result might be affected
# by changes to the managed resource.
object_id = test_resource.a.id
}
data "test_data_source" "a" {
id = local.object_id
}
resource "test_resource" "b" {
valid = true
lifecycle {
precondition {
condition = data.test_data_source.a.valid
error_message = "Not valid!"
}
}
}
`})
managedAddrA := mustResourceInstanceAddr(`test_resource.a`)
managedAddrB := mustResourceInstanceAddr(`test_resource.b`)
// This state is intended to represent the outcome of a previous apply that
// failed due to postcondition failure but had already updated the
// relevant object to be invalid.
//
// It could also potentially represent a similar situation where the
// previous apply succeeded but there has been a change outside of
// Terraform that made it invalid, although technically in that scenario
// the state data would become invalid only during the planning step. For
// our purposes here that's close enough because we don't have a real
// remote system in place anyway.
priorState := states.BuildState(func(s *states.SyncState) {
s.SetResourceInstanceCurrent(
managedAddrA,
&states.ResourceInstanceObjectSrc{
// NOTE: "valid" is false here but is true in the configuration
// above, which is intended to represent that applying the
// configuration change would make this object become valid.
AttrsJSON: []byte(`{"id":"main","valid":false}`),
Status: states.ObjectReady,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`),
)
s.SetResourceInstanceCurrent(
managedAddrB,
&states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"id":"checker","valid":true}`),
Status: states.ObjectReady,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`),
)
})
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
_, diags := ctx.Plan(m, priorState, DefaultPlanOpts)
if !diags.HasErrors() {
t.Fatalf("unexpected successful plan; should've failed with non-passing precondition")
}
if got, want := diags.Err().Error(), "Resource precondition failed: Not valid!"; !strings.Contains(got, want) {
t.Errorf("Missing expected error message\ngot: %s\nwant substring: %s", got, want)
}
}
func TestContext2Plan_destroyWithRefresh(t *testing.T) {
m := testModuleInline(t, map[string]string{
"main.tf": `
resource "test_object" "a" {
}
`,
})
p := simpleMockProvider()
p.GetProviderSchemaResponse = &providers.GetProviderSchemaResponse{
Provider: providers.Schema{Block: simpleTestSchema()},
ResourceTypes: map[string]providers.Schema{
"test_object": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"arg": {Type: cty.String, Optional: true},
},
},
},
},
}
// This is called from the first instance of this provider, so we can't
// check p.ReadResourceCalled after plan.
readResourceCalled := false
p.ReadResourceFn = func(req providers.ReadResourceRequest) (resp providers.ReadResourceResponse) {
readResourceCalled = true
newVal, err := cty.Transform(req.PriorState, func(path cty.Path, v cty.Value) (cty.Value, error) {
if len(path) == 1 && path[0] == (cty.GetAttrStep{Name: "arg"}) {
return cty.StringVal("current"), nil
}
return v, nil
})
if err != nil {
// shouldn't get here
t.Fatalf("ReadResourceFn transform failed")
return providers.ReadResourceResponse{}
}
return providers.ReadResourceResponse{
NewState: newVal,
}
}
upgradeResourceStateCalled := false
p.UpgradeResourceStateFn = func(req providers.UpgradeResourceStateRequest) (resp providers.UpgradeResourceStateResponse) {
upgradeResourceStateCalled = true
t.Logf("UpgradeResourceState %s", req.RawStateJSON)
// In the destroy-with-refresh codepath we end up calling
// UpgradeResourceState twice, because we do so once during refreshing
// (as part making a normal plan) and then again during the plan-destroy
// walk. The second call recieves the result of the earlier refresh,
// so we need to tolerate both "before" and "current" as possible
// inputs here.
if !bytes.Contains(req.RawStateJSON, []byte("before")) {
if !bytes.Contains(req.RawStateJSON, []byte("current")) {
t.Fatalf("UpgradeResourceState request doesn't contain the 'before' object or the 'current' object\n%s", req.RawStateJSON)
}
}
// We'll put something different in "arg" as part of upgrading, just
// so that we can verify below that PrevRunState contains the upgraded
// (but NOT refreshed) version of the object.
resp.UpgradedState = cty.ObjectVal(map[string]cty.Value{
"arg": cty.StringVal("upgraded"),
})
return resp
}
addr := mustResourceInstanceAddr("test_object.a")
state := states.BuildState(func(s *states.SyncState) {
s.SetResourceInstanceCurrent(addr, &states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"arg":"before"}`),
Status: states.ObjectReady,
}, mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`))
})
ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})
plan, diags := ctx.Plan(m, state, &PlanOpts{
Mode: plans.DestroyMode,
SkipRefresh: false, // the default
})
assertNoErrors(t, diags)
if !upgradeResourceStateCalled {
t.Errorf("Provider's UpgradeResourceState wasn't called; should've been")
}
if !readResourceCalled {
t.Errorf("Provider's ReadResource wasn't called; should've been")
}