-
Notifications
You must be signed in to change notification settings - Fork 233
/
resource.go
1427 lines (1274 loc) · 55 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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package schema
import (
"context"
"errors"
"fmt"
"strconv"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)
var ReservedDataSourceFields = []string{
"connection",
"count",
"depends_on",
"lifecycle",
"provider",
"provisioner",
}
var ReservedResourceFields = []string{
"connection",
"count",
"depends_on",
"lifecycle",
"provider",
"provisioner",
}
// Resource is an abstraction for multiple Terraform concepts:
//
// - Managed Resource: An infrastructure component with a schema, lifecycle
// operations such as create, read, update, and delete
// (CRUD), and optional implementation details such as
// import support, upgrade state support, and difference
// customization.
// - Data Resource: Also known as a data source. An infrastructure component
// with a schema and only the read lifecycle operation.
// - Block: When implemented within a Schema type Elem field, a configuration
// block that contains nested schema information such as attributes
// and blocks.
//
// To fully implement managed resources, the Provider type ResourcesMap field
// should include a reference to an implementation of this type. To fully
// implement data resources, the Provider type DataSourcesMap field should
// include a reference to an implementation of this type.
//
// Each field further documents any constraints based on the Terraform concept
// being implemented.
type Resource struct {
// Schema is the structure and type information for this component. This
// field, or SchemaFunc, is required for all Resource concepts. To prevent
// storing all schema information in memory for the lifecycle of a provider,
// use SchemaFunc instead.
//
// The keys of this map are the names used in a practitioner configuration,
// such as the attribute or block name. The values describe the structure
// and type information of that attribute or block.
Schema map[string]*Schema
// SchemaFunc is the structure and type information for this component. This
// field, or Schema, is required for all Resource concepts. Use this field
// instead of Schema on top level Resource declarations to prevent storing
// all schema information in memory for the lifecycle of a provider.
//
// The keys of this map are the names used in a practitioner configuration,
// such as the attribute or block name. The values describe the structure
// and type information of that attribute or block.
SchemaFunc func() map[string]*Schema
// SchemaVersion is the version number for this resource's Schema
// definition. This field is only valid when the Resource is a managed
// resource.
//
// The current SchemaVersion stored in the state for each resource.
// Provider authors can increment this version number when Schema semantics
// change in an incompatible manner. If the state's SchemaVersion is less
// than the current SchemaVersion, the MigrateState and StateUpgraders
// functionality is executed to upgrade the state information.
//
// When unset, SchemaVersion defaults to 0, so provider authors can start
// their Versioning at any integer >= 1
SchemaVersion int
// MigrateState is responsible for updating an InstanceState with an old
// version to the format expected by the current version of the Schema.
// This field is only valid when the Resource is a managed resource.
//
// It is called during Refresh if the State's stored SchemaVersion is less
// than the current SchemaVersion of the Resource.
//
// The function is yielded the state's stored SchemaVersion and a pointer to
// the InstanceState that needs updating, as well as the configured
// provider's configured meta interface{}, in case the migration process
// needs to make any remote API calls.
//
// Deprecated: MigrateState is deprecated and any new changes to a resource's schema
// should be handled by StateUpgraders. Existing MigrateState implementations
// should remain for compatibility with existing state. MigrateState will
// still be called if the stored SchemaVersion is less than the
// first version of the StateUpgraders.
MigrateState StateMigrateFunc
// StateUpgraders contains the functions responsible for upgrading an
// existing state with an old schema version to a newer schema. It is
// called specifically by Terraform when the stored schema version is less
// than the current SchemaVersion of the Resource. This field is only valid
// when the Resource is a managed resource.
//
// StateUpgraders map specific schema versions to a StateUpgrader
// function. The registered versions are expected to be ordered,
// consecutive values. The initial value may be greater than 0 to account
// for legacy schemas that weren't recorded and can be handled by
// MigrateState.
StateUpgraders []StateUpgrader
// Create is called when the provider must create a new instance of a
// managed resource. This field is only valid when the Resource is a
// managed resource. Only one of Create, CreateContext, or
// CreateWithoutTimeout should be implemented.
//
// The *ResourceData parameter contains the plan and state data for this
// managed resource instance. The available data in the Get* methods is the
// the proposed state, which is the merged data of the practitioner
// configuration and any CustomizeDiff field logic.
//
// The SetId method must be called with a non-empty value for the managed
// resource instance to be properly saved into the Terraform state and
// avoid a "inconsistent result after apply" error.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The error return parameter, if not nil, will be converted into an error
// diagnostic when passed back to Terraform.
//
// Deprecated: Use CreateContext or CreateWithoutTimeout instead. This
// implementation does not support request cancellation initiated by
// Terraform, such as a system or practitioner sending SIGINT (Ctrl-c).
// This implementation also does not support warning diagnostics.
Create CreateFunc
// Read is called when the provider must refresh the state of a managed
// resource instance or data resource instance. This field is only valid
// when the Resource is a managed resource or data resource. Only one of
// Read, ReadContext, or ReadWithoutTimeout should be implemented.
//
// The *ResourceData parameter contains the state data for this managed
// resource instance or data resource instance.
//
// Managed resources can signal to Terraform that the managed resource
// instance no longer exists and potentially should be recreated by calling
// the SetId method with an empty string ("") parameter and without
// returning an error.
//
// Data resources that are designed to return state for a singular
// infrastructure component should conventionally return an error if that
// infrastructure does not exist and omit any calls to the
// SetId method.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The error return parameter, if not nil, will be converted into an error
// diagnostic when passed back to Terraform.
//
// Deprecated: Use ReadContext or ReadWithoutTimeout instead. This
// implementation does not support request cancellation initiated by
// Terraform, such as a system or practitioner sending SIGINT (Ctrl-c).
// This implementation also does not support warning diagnostics.
Read ReadFunc
// Update is called when the provider must update an instance of a
// managed resource. This field is only valid when the Resource is a
// managed resource. Only one of Update, UpdateContext, or
// UpdateWithoutTimeout should be implemented.
//
// This implementation is optional. If omitted, all Schema must enable
// the ForceNew field and any practitioner changes that would have
// caused and update will instead destroy and recreate the infrastructure
// component.
//
// The *ResourceData parameter contains the plan and state data for this
// managed resource instance. The available data in the Get* methods is the
// the proposed state, which is the merged data of the prior state,
// practitioner configuration, and any CustomizeDiff field logic. The
// available data for the GetChange* and HasChange* methods is the prior
// state and proposed state.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The error return parameter, if not nil, will be converted into an error
// diagnostic when passed back to Terraform.
//
// Deprecated: Use UpdateContext or UpdateWithoutTimeout instead. This
// implementation does not support request cancellation initiated by
// Terraform, such as a system or practitioner sending SIGINT (Ctrl-c).
// This implementation also does not support warning diagnostics.
Update UpdateFunc
// Delete is called when the provider must destroy the instance of a
// managed resource. This field is only valid when the Resource is a
// managed resource. Only one of Delete, DeleteContext, or
// DeleteWithoutTimeout should be implemented.
//
// The *ResourceData parameter contains the state data for this managed
// resource instance.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The error return parameter, if not nil, will be converted into an error
// diagnostic when passed back to Terraform.
//
// Deprecated: Use DeleteContext or DeleteWithoutTimeout instead. This
// implementation does not support request cancellation initiated by
// Terraform, such as a system or practitioner sending SIGINT (Ctrl-c).
// This implementation also does not support warning diagnostics.
Delete DeleteFunc
// Exists is a function that is called to check if a resource still
// exists. This field is only valid when the Resource is a managed
// resource.
//
// If this returns false, then this will affect the diff
// accordingly. If this function isn't set, it will not be called. You
// can also signal existence in the Read method by calling d.SetId("")
// if the Resource is no longer present and should be removed from state.
// The *ResourceData passed to Exists should _not_ be modified.
//
// Deprecated: Remove in preference of ReadContext or ReadWithoutTimeout.
Exists ExistsFunc
// CreateContext is called when the provider must create a new instance of
// a managed resource. This field is only valid when the Resource is a
// managed resource. Only one of Create, CreateContext, or
// CreateWithoutTimeout should be implemented.
//
// The Context parameter stores SDK information, such as loggers and
// timeout deadlines. It also is wired to receive any cancellation from
// Terraform such as a system or practitioner sending SIGINT (Ctrl-c).
//
// By default, CreateContext has a 20 minute timeout. Use the Timeouts
// field to control the default duration or implement CreateWithoutTimeout
// instead of CreateContext to remove the default timeout.
//
// The *ResourceData parameter contains the plan and state data for this
// managed resource instance. The available data in the Get* methods is the
// the proposed state, which is the merged data of the practitioner
// configuration and any CustomizeDiff field logic.
//
// The SetId method must be called with a non-empty value for the managed
// resource instance to be properly saved into the Terraform state and
// avoid a "inconsistent result after apply" error.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The diagnostics return parameter, if not nil, can contain any
// combination and multiple of warning and/or error diagnostics.
CreateContext CreateContextFunc
// ReadContext is called when the provider must refresh the state of a managed
// resource instance or data resource instance. This field is only valid
// when the Resource is a managed resource or data resource. Only one of
// Read, ReadContext, or ReadWithoutTimeout should be implemented.
//
// The Context parameter stores SDK information, such as loggers and
// timeout deadlines. It also is wired to receive any cancellation from
// Terraform such as a system or practitioner sending SIGINT (Ctrl-c).
//
// By default, ReadContext has a 20 minute timeout. Use the Timeouts
// field to control the default duration or implement ReadWithoutTimeout
// instead of ReadContext to remove the default timeout.
//
// The *ResourceData parameter contains the state data for this managed
// resource instance or data resource instance.
//
// Managed resources can signal to Terraform that the managed resource
// instance no longer exists and potentially should be recreated by calling
// the SetId method with an empty string ("") parameter and without
// returning an error.
//
// Data resources that are designed to return state for a singular
// infrastructure component should conventionally return an error if that
// infrastructure does not exist and omit any calls to the
// SetId method.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The diagnostics return parameter, if not nil, can contain any
// combination and multiple of warning and/or error diagnostics.
ReadContext ReadContextFunc
// UpdateContext is called when the provider must update an instance of a
// managed resource. This field is only valid when the Resource is a
// managed resource. Only one of Update, UpdateContext, or
// UpdateWithoutTimeout should be implemented.
//
// This implementation is optional. If omitted, all Schema must enable
// the ForceNew field and any practitioner changes that would have
// caused and update will instead destroy and recreate the infrastructure
// component.
//
// The Context parameter stores SDK information, such as loggers and
// timeout deadlines. It also is wired to receive any cancellation from
// Terraform such as a system or practitioner sending SIGINT (Ctrl-c).
//
// By default, UpdateContext has a 20 minute timeout. Use the Timeouts
// field to control the default duration or implement UpdateWithoutTimeout
// instead of UpdateContext to remove the default timeout.
//
// The *ResourceData parameter contains the plan and state data for this
// managed resource instance. The available data in the Get* methods is the
// the proposed state, which is the merged data of the prior state,
// practitioner configuration, and any CustomizeDiff field logic. The
// available data for the GetChange* and HasChange* methods is the prior
// state and proposed state.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The diagnostics return parameter, if not nil, can contain any
// combination and multiple of warning and/or error diagnostics.
UpdateContext UpdateContextFunc
// DeleteContext is called when the provider must destroy the instance of a
// managed resource. This field is only valid when the Resource is a
// managed resource. Only one of Delete, DeleteContext, or
// DeleteWithoutTimeout should be implemented.
//
// The Context parameter stores SDK information, such as loggers and
// timeout deadlines. It also is wired to receive any cancellation from
// Terraform such as a system or practitioner sending SIGINT (Ctrl-c).
//
// By default, DeleteContext has a 20 minute timeout. Use the Timeouts
// field to control the default duration or implement DeleteWithoutTimeout
// instead of DeleteContext to remove the default timeout.
//
// The *ResourceData parameter contains the state data for this managed
// resource instance.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The diagnostics return parameter, if not nil, can contain any
// combination and multiple of warning and/or error diagnostics.
DeleteContext DeleteContextFunc
// CreateWithoutTimeout is called when the provider must create a new
// instance of a managed resource. This field is only valid when the
// Resource is a managed resource. Only one of Create, CreateContext, or
// CreateWithoutTimeout should be implemented.
//
// Most resources should prefer CreateContext with properly implemented
// operation timeout values, however there are cases where operation
// synchronization across concurrent resources is necessary in the resource
// logic, such as a mutex, to prevent remote system errors. Since these
// operations would have an indeterminate timeout that scales with the
// number of resources, this allows resources to control timeout behavior.
//
// The Context parameter stores SDK information, such as loggers. It also
// is wired to receive any cancellation from Terraform such as a system or
// practitioner sending SIGINT (Ctrl-c).
//
// The *ResourceData parameter contains the plan and state data for this
// managed resource instance. The available data in the Get* methods is the
// the proposed state, which is the merged data of the practitioner
// configuration and any CustomizeDiff field logic.
//
// The SetId method must be called with a non-empty value for the managed
// resource instance to be properly saved into the Terraform state and
// avoid a "inconsistent result after apply" error.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The diagnostics return parameter, if not nil, can contain any
// combination and multiple of warning and/or error diagnostics.
CreateWithoutTimeout CreateContextFunc
// ReadWithoutTimeout is called when the provider must refresh the state of
// a managed resource instance or data resource instance. This field is
// only valid when the Resource is a managed resource or data resource.
// Only one of Read, ReadContext, or ReadWithoutTimeout should be
// implemented.
//
// Most resources should prefer ReadContext with properly implemented
// operation timeout values, however there are cases where operation
// synchronization across concurrent resources is necessary in the resource
// logic, such as a mutex, to prevent remote system errors. Since these
// operations would have an indeterminate timeout that scales with the
// number of resources, this allows resources to control timeout behavior.
//
// The Context parameter stores SDK information, such as loggers. It also
// is wired to receive any cancellation from Terraform such as a system or
// practitioner sending SIGINT (Ctrl-c).
//
// The *ResourceData parameter contains the state data for this managed
// resource instance or data resource instance.
//
// Managed resources can signal to Terraform that the managed resource
// instance no longer exists and potentially should be recreated by calling
// the SetId method with an empty string ("") parameter and without
// returning an error.
//
// Data resources that are designed to return state for a singular
// infrastructure component should conventionally return an error if that
// infrastructure does not exist and omit any calls to the
// SetId method.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The diagnostics return parameter, if not nil, can contain any
// combination and multiple of warning and/or error diagnostics.
ReadWithoutTimeout ReadContextFunc
// UpdateWithoutTimeout is called when the provider must update an instance
// of a managed resource. This field is only valid when the Resource is a
// managed resource. Only one of Update, UpdateContext, or
// UpdateWithoutTimeout should be implemented.
//
// Most resources should prefer UpdateContext with properly implemented
// operation timeout values, however there are cases where operation
// synchronization across concurrent resources is necessary in the resource
// logic, such as a mutex, to prevent remote system errors. Since these
// operations would have an indeterminate timeout that scales with the
// number of resources, this allows resources to control timeout behavior.
//
// This implementation is optional. If omitted, all Schema must enable
// the ForceNew field and any practitioner changes that would have
// caused and update will instead destroy and recreate the infrastructure
// component.
//
// The Context parameter stores SDK information, such as loggers. It also
// is wired to receive any cancellation from Terraform such as a system or
// practitioner sending SIGINT (Ctrl-c).
//
// The *ResourceData parameter contains the plan and state data for this
// managed resource instance. The available data in the Get* methods is the
// the proposed state, which is the merged data of the prior state,
// practitioner configuration, and any CustomizeDiff field logic. The
// available data for the GetChange* and HasChange* methods is the prior
// state and proposed state.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The diagnostics return parameter, if not nil, can contain any
// combination and multiple of warning and/or error diagnostics.
UpdateWithoutTimeout UpdateContextFunc
// DeleteWithoutTimeout is called when the provider must destroy the
// instance of a managed resource. This field is only valid when the
// Resource is a managed resource. Only one of Delete, DeleteContext, or
// DeleteWithoutTimeout should be implemented.
//
// Most resources should prefer DeleteContext with properly implemented
// operation timeout values, however there are cases where operation
// synchronization across concurrent resources is necessary in the resource
// logic, such as a mutex, to prevent remote system errors. Since these
// operations would have an indeterminate timeout that scales with the
// number of resources, this allows resources to control timeout behavior.
//
// The Context parameter stores SDK information, such as loggers. It also
// is wired to receive any cancellation from Terraform such as a system or
// practitioner sending SIGINT (Ctrl-c).
//
// The *ResourceData parameter contains the state data for this managed
// resource instance.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The diagnostics return parameter, if not nil, can contain any
// combination and multiple of warning and/or error diagnostics.
DeleteWithoutTimeout DeleteContextFunc
// CustomizeDiff is called after a difference (plan) has been generated
// for the Resource and allows for customizations, such as setting values
// not controlled by configuration, conditionally triggering resource
// recreation, or implementing additional validation logic to abort a plan.
// This field is only valid when the Resource is a managed resource.
//
// The Context parameter stores SDK information, such as loggers. It also
// is wired to receive any cancellation from Terraform such as a system or
// practitioner sending SIGINT (Ctrl-c).
//
// The *ResourceDiff parameter is similar to ResourceData but replaces the
// Set method with other difference handling methods, such as SetNew,
// SetNewComputed, and ForceNew. In general, only Schema with Computed
// enabled can have those methods executed against them.
//
// The phases Terraform runs this in, and the state available via functions
// like Get and GetChange, are as follows:
//
// * New resource: One run with no state
// * Existing resource: One run with state
// * Existing resource, forced new: One run with state (before ForceNew),
// then one run without state (as if new resource)
// * Tainted resource: No runs (custom diff logic is skipped)
// * Destroy: No runs (standard diff logic is skipped on destroy diffs)
//
// This function needs to be resilient to support all scenarios.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The error return parameter, if not nil, will be converted into an error
// diagnostic when passed back to Terraform.
CustomizeDiff CustomizeDiffFunc
// Importer is called when the provider must import an instance of a
// managed resource. This field is only valid when the Resource is a
// managed resource.
//
// If this is nil, then this resource does not support importing. If
// this is non-nil, then it supports importing and ResourceImporter
// must be validated. The validity of ResourceImporter is verified
// by InternalValidate on Resource.
Importer *ResourceImporter
// If non-empty, this string is emitted as the details of a warning
// diagnostic during validation (validate, plan, and apply operations).
// This field is only valid when the Resource is a managed resource or
// data resource.
DeprecationMessage string
// Timeouts configures the default time duration allowed before a create,
// read, update, or delete operation is considered timed out, which returns
// an error to practitioners. This field is only valid when the Resource is
// a managed resource or data resource.
//
// When implemented, practitioners can add a timeouts configuration block
// within their managed resource or data resource configuration to further
// customize the create, read, update, or delete operation timeouts. For
// example, a configuration may specify a longer create timeout for a
// database resource due to its data size.
//
// The ResourceData that is passed to create, read, update, and delete
// functionality can access the merged time duration of the Resource
// default timeouts configured in this field and the practitioner timeouts
// configuration via the Timeout method. Practitioner configuration
// always overrides any default values set here, whether shorter or longer.
Timeouts *ResourceTimeout
// Description is used as the description for docs, the language server and
// other user facing usage. It can be plain-text or markdown depending on the
// global DescriptionKind setting. This field is valid for any Resource.
Description string
// UseJSONNumber should be set when state upgraders will expect
// json.Numbers instead of float64s for numbers. This is added as a
// toggle for backwards compatibility for type assertions, but should
// be used in all new resources to avoid bugs with sufficiently large
// user input. This field is only valid when the Resource is a managed
// resource.
//
// See github.com/hashicorp/terraform-plugin-sdk/issues/655 for more
// details.
UseJSONNumber bool
// EnableLegacyTypeSystemApplyErrors when enabled will prevent the SDK from
// setting the legacy type system flag in the protocol during
// ApplyResourceChange (Create, Update, and Delete) operations. Before
// enabling this setting in a production release for a resource, the
// resource should be exhaustively acceptance tested with the setting
// enabled in an environment where it is easy to clean up resources,
// potentially outside of Terraform, since these errors may be unavoidable
// in certain cases.
//
// Disabling the legacy type system protocol flag is an unsafe operation
// when using this SDK as there are certain unavoidable behaviors imposed
// by the SDK, however this option is surfaced to allow provider developers
// to try to discover fixable data inconsistency errors more easily.
// Terraform, when encountering an enabled legacy type system protocol flag,
// will demote certain schema and data consistency errors into warning logs
// containing the text "legacy plugin SDK". Some errors for errant schema
// definitions, such as when an attribute is not marked as Computed as
// expected by Terraform, can only be resolved by migrating to
// terraform-plugin-framework since that SDK does not impose behavior
// changes with it enabled. However, data-based errors typically require
// logic fixes that should be applicable for both SDKs to be resolved.
EnableLegacyTypeSystemApplyErrors bool
// EnableLegacyTypeSystemPlanErrors when enabled will prevent the SDK from
// setting the legacy type system flag in the protocol during
// PlanResourceChange operations. Before enabling this setting in a
// production release for a resource, the resource should be exhaustively
// acceptance tested with the setting enabled in an environment where it is
// easy to clean up resources, potentially outside of Terraform, since these
// errors may be unavoidable in certain cases.
//
// Disabling the legacy type system protocol flag is an unsafe operation
// when using this SDK as there are certain unavoidable behaviors imposed
// by the SDK, however this option is surfaced to allow provider developers
// to try to discover fixable data inconsistency errors more easily.
// Terraform, when encountering an enabled legacy type system protocol flag,
// will demote certain schema and data consistency errors into warning logs
// containing the text "legacy plugin SDK". Some errors for errant schema
// definitions, such as when an attribute is not marked as Computed as
// expected by Terraform, can only be resolved by migrating to
// terraform-plugin-framework since that SDK does not impose behavior
// changes with it enabled. However, data-based errors typically require
// logic fixes that should be applicable for both SDKs to be resolved.
EnableLegacyTypeSystemPlanErrors bool
// ResourceBehavior is used to control SDK-specific logic when
// interacting with this resource.
ResourceBehavior ResourceBehavior
}
// ResourceBehavior controls SDK-specific logic when interacting
// with a resource.
type ResourceBehavior struct {
// ProviderDeferred enables provider-defined logic to be executed
// in the case of a deferred response from (Provider).ConfigureProvider.
//
// NOTE: This functionality is related to deferred action support, which is currently experimental and is subject
// to change or break without warning. It is not protected by version compatibility guarantees.
ProviderDeferred ProviderDeferredBehavior
}
// ProviderDeferredBehavior enables provider-defined logic to be executed
// in the case of a deferred response from provider configuration.
//
// NOTE: This functionality is related to deferred action support, which is currently experimental and is subject
// to change or break without warning. It is not protected by version compatibility guarantees.
type ProviderDeferredBehavior struct {
// When EnablePlanModification is true, the SDK will execute provider-defined logic
// during plan (CustomizeDiff, Default, DiffSuppressFunc, etc.) if ConfigureProvider
// returns a deferred response. The SDK will then automatically return a deferred response
// along with the modified plan.
EnablePlanModification bool
}
// SchemaMap returns the schema information for this Resource whether it is
// defined via the SchemaFunc field or Schema field. The SchemaFunc field, if
// defined, takes precedence over the Schema field.
func (r *Resource) SchemaMap() map[string]*Schema {
if r.SchemaFunc != nil {
return r.SchemaFunc()
}
return r.Schema
}
// ShimInstanceStateFromValue converts a cty.Value to a
// terraform.InstanceState.
func (r *Resource) ShimInstanceStateFromValue(state cty.Value) (*terraform.InstanceState, error) {
// Get the raw shimmed value. While this is correct, the set hashes don't
// match those from the Schema.
s := terraform.NewInstanceStateShimmedFromValue(state, r.SchemaVersion)
// We now rebuild the state through the ResourceData, so that the set indexes
// match what helper/schema expects.
data, err := schemaMap(r.SchemaMap()).Data(s, nil)
if err != nil {
return nil, err
}
s = data.State()
if s == nil {
s = &terraform.InstanceState{}
}
return s, nil
}
// The following function types are of the legacy CRUD operations.
//
// Deprecated: Please use the context aware equivalents instead.
type CreateFunc func(*ResourceData, interface{}) error
// Deprecated: Please use the context aware equivalents instead.
type ReadFunc func(*ResourceData, interface{}) error
// Deprecated: Please use the context aware equivalents instead.
type UpdateFunc func(*ResourceData, interface{}) error
// Deprecated: Please use the context aware equivalents instead.
type DeleteFunc func(*ResourceData, interface{}) error
// Deprecated: Please use the context aware equivalents instead.
type ExistsFunc func(*ResourceData, interface{}) (bool, error)
// See Resource documentation.
type CreateContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics
// See Resource documentation.
type ReadContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics
// See Resource documentation.
type UpdateContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics
// See Resource documentation.
type DeleteContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics
// See Resource documentation.
type StateMigrateFunc func(
int, *terraform.InstanceState, interface{}) (*terraform.InstanceState, error)
// Implementation of a single schema version state upgrade.
type StateUpgrader struct {
// Version is the version schema that this Upgrader will handle, converting
// it to Version+1.
Version int
// Type describes the schema that this function can upgrade. Type is
// required to decode the schema if the state was stored in a legacy
// flatmap format.
Type cty.Type
// Upgrade takes the JSON encoded state and the provider meta value, and
// upgrades the state one single schema version. The provided state is
// decoded into the default json types using a map[string]interface{}. It
// is up to the StateUpgradeFunc to ensure that the returned value can be
// encoded using the new schema.
Upgrade StateUpgradeFunc
}
// Function signature for a schema version state upgrade handler.
//
// The Context parameter stores SDK information, such as loggers. It also
// is wired to receive any cancellation from Terraform such as a system or
// practitioner sending SIGINT (Ctrl-c).
//
// The map[string]interface{} parameter contains the previous schema version
// state data for a managed resource instance. The keys are top level attribute
// or block names mapped to values that can be type asserted similar to
// fetching values using the ResourceData Get* methods:
//
// - TypeBool: bool
// - TypeFloat: float
// - TypeInt: int
// - TypeList: []interface{}
// - TypeMap: map[string]interface{}
// - TypeSet: *Set
// - TypeString: string
//
// In certain scenarios, the map may be nil, so checking for that condition
// upfront is recommended to prevent potential panics.
//
// The interface{} parameter is the result of the Provider type
// ConfigureFunc field execution. If the Provider does not define
// a ConfigureFunc, this will be nil. This parameter is conventionally
// used to store API clients and other provider instance specific data.
//
// The map[string]interface{} return parameter should contain the upgraded
// schema version state data for a managed resource instance. Values must
// align to the typing mentioned above.
type StateUpgradeFunc func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error)
// See Resource documentation.
type CustomizeDiffFunc func(context.Context, *ResourceDiff, interface{}) error
func (r *Resource) create(ctx context.Context, d *ResourceData, meta interface{}) diag.Diagnostics {
if r.Create != nil {
if err := r.Create(d, meta); err != nil {
return diag.FromErr(err)
}
return nil
}
if r.CreateWithoutTimeout != nil {
return r.CreateWithoutTimeout(ctx, d, meta)
}
ctx, cancel := context.WithTimeout(ctx, d.Timeout(TimeoutCreate))
defer cancel()
return r.CreateContext(ctx, d, meta)
}
func (r *Resource) read(ctx context.Context, d *ResourceData, meta interface{}) diag.Diagnostics {
if r.Read != nil {
if err := r.Read(d, meta); err != nil {
return diag.FromErr(err)
}
return nil
}
if r.ReadWithoutTimeout != nil {
return r.ReadWithoutTimeout(ctx, d, meta)
}
ctx, cancel := context.WithTimeout(ctx, d.Timeout(TimeoutRead))
defer cancel()
return r.ReadContext(ctx, d, meta)
}
func (r *Resource) update(ctx context.Context, d *ResourceData, meta interface{}) diag.Diagnostics {
if r.Update != nil {
if err := r.Update(d, meta); err != nil {
return diag.FromErr(err)
}
return nil
}
if r.UpdateWithoutTimeout != nil {
return r.UpdateWithoutTimeout(ctx, d, meta)
}
ctx, cancel := context.WithTimeout(ctx, d.Timeout(TimeoutUpdate))
defer cancel()
return r.UpdateContext(ctx, d, meta)
}
func (r *Resource) delete(ctx context.Context, d *ResourceData, meta interface{}) diag.Diagnostics {
if r.Delete != nil {
if err := r.Delete(d, meta); err != nil {
return diag.FromErr(err)
}
return nil
}
if r.DeleteWithoutTimeout != nil {
return r.DeleteWithoutTimeout(ctx, d, meta)
}
ctx, cancel := context.WithTimeout(ctx, d.Timeout(TimeoutDelete))
defer cancel()
return r.DeleteContext(ctx, d, meta)
}
// Apply creates, updates, and/or deletes a resource.
func (r *Resource) Apply(
ctx context.Context,
s *terraform.InstanceState,
d *terraform.InstanceDiff,
meta interface{}) (*terraform.InstanceState, diag.Diagnostics) {
schema := schemaMap(r.SchemaMap())
data, err := schema.Data(s, d)
if err != nil {
return s, diag.FromErr(err)
}
if s != nil && data != nil {
data.providerMeta = s.ProviderMeta
}
// Instance Diff should have the timeout info, need to copy it over to the
// ResourceData meta
rt := ResourceTimeout{}
if _, ok := d.Meta[TimeoutKey]; ok {
if err := rt.DiffDecode(d); err != nil {
logging.HelperSchemaError(ctx, "Error decoding ResourceTimeout", map[string]interface{}{logging.KeyError: err})
}
} else if s != nil {
if _, ok := s.Meta[TimeoutKey]; ok {
if err := rt.StateDecode(s); err != nil {
logging.HelperSchemaError(ctx, "Error decoding ResourceTimeout", map[string]interface{}{logging.KeyError: err})
}
}
} else {
logging.HelperSchemaDebug(ctx, "No meta timeoutkey found in Apply()")
}
data.timeouts = &rt
if s == nil {
// The Terraform API dictates that this should never happen, but
// it doesn't hurt to be safe in this case.
s = new(terraform.InstanceState)
}
var diags diag.Diagnostics
if d.Destroy || d.RequiresNew() {
if s.ID != "" {
// Destroy the resource since it is created
logging.HelperSchemaTrace(ctx, "Calling downstream")
diags = append(diags, r.delete(ctx, data, meta)...)
logging.HelperSchemaTrace(ctx, "Called downstream")
if diags.HasError() {
return r.recordCurrentSchemaVersion(data.State()), diags
}
// Make sure the ID is gone.
data.SetId("")
}
// If we're only destroying, and not creating, then return
// now since we're done!
if !d.RequiresNew() {
return nil, diags
}
// Reset the data to be stateless since we just destroyed
data, err = schema.Data(nil, d)
if err != nil {
return nil, append(diags, diag.FromErr(err)...)
}
// data was reset, need to re-apply the parsed timeouts
data.timeouts = &rt
}
if data.Id() == "" {
// We're creating, it is a new resource.
data.MarkNewResource()
logging.HelperSchemaTrace(ctx, "Calling downstream")
diags = append(diags, r.create(ctx, data, meta)...)
logging.HelperSchemaTrace(ctx, "Called downstream")
} else {
if !r.updateFuncSet() {
return s, append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: "doesn't support update",
})
}
logging.HelperSchemaTrace(ctx, "Calling downstream")
diags = append(diags, r.update(ctx, data, meta)...)
logging.HelperSchemaTrace(ctx, "Called downstream")
}
return r.recordCurrentSchemaVersion(data.State()), diags
}
// Diff returns a diff of this resource.
func (r *Resource) Diff(
ctx context.Context,
s *terraform.InstanceState,
c *terraform.ResourceConfig,
meta interface{}) (*terraform.InstanceDiff, error) {
t := &ResourceTimeout{}
err := t.ConfigDecode(r, c)
if err != nil {
return nil, fmt.Errorf("[ERR] Error decoding timeout: %s", err)
}
instanceDiff, err := schemaMap(r.SchemaMap()).Diff(ctx, s, c, r.CustomizeDiff, meta, true)
if err != nil {
return instanceDiff, err
}
if instanceDiff != nil {
if err := t.DiffEncode(instanceDiff); err != nil {
logging.HelperSchemaError(ctx, "Error encoding timeout to instance diff", map[string]interface{}{logging.KeyError: err})
}
} else {
logging.HelperSchemaDebug(ctx, "Instance Diff is nil in Diff()")
}
return instanceDiff, err
}
func (r *Resource) SimpleDiff(
ctx context.Context,
s *terraform.InstanceState,
c *terraform.ResourceConfig,
meta interface{}) (*terraform.InstanceDiff, error) {
instanceDiff, err := schemaMap(r.SchemaMap()).Diff(ctx, s, c, r.CustomizeDiff, meta, false)
if err != nil {
return instanceDiff, err
}
if instanceDiff == nil {
instanceDiff = terraform.NewInstanceDiff()
}
// Make sure the old value is set in each of the instance diffs.
// This was done by the RequiresNew logic in the full legacy Diff.