-
Notifications
You must be signed in to change notification settings - Fork 17
/
provider.go
1431 lines (1196 loc) · 42.7 KB
/
provider.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 The Terranova Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package terranova
import (
"encoding/json"
"fmt"
"log"
"strconv"
"sync"
"github.com/hashicorp/terraform/configs/configschema"
"github.com/hashicorp/terraform/configs/hcl2shim"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/plans/objchange"
"github.com/hashicorp/terraform/providers"
"github.com/hashicorp/terraform/terraform"
"github.com/hashicorp/terraform/tfdiags"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
)
const newExtraKey = "_new_extra_shim"
// Provider implements the provider.Interface wrapping the legacy
// ResourceProvider but not using gRPC like terraform does
type Provider struct {
provider *schema.Provider
mu sync.Mutex
schemas providers.GetSchemaResponse
}
// NewProvider creates a Terranova Provider to wrap the given legacy ResourceProvider
func NewProvider(provider terraform.ResourceProvider) *Provider {
sp, ok := provider.(*schema.Provider)
if !ok {
return nil
}
return &Provider{
provider: sp,
}
}
func providersFactory(rp terraform.ResourceProvider) providers.Factory {
p := NewProvider(rp)
return providers.FactoryFixed(p)
}
// GetSchema implements the GetSchema from providers.Interface. Returns the
// complete schema for the provider.
func (p *Provider) GetSchema() (resp providers.GetSchemaResponse) {
p.mu.Lock()
defer p.mu.Unlock()
if p.schemas.Provider.Block != nil {
return p.schemas
}
resp = providers.GetSchemaResponse{
ResourceTypes: make(map[string]providers.Schema),
DataSources: make(map[string]providers.Schema),
}
resp.Provider = providers.Schema{
// Version: p.provider.Schema.Version,
Block: schema.InternalMap(p.provider.Schema).CoreConfigSchema(),
}
for name, resource := range p.provider.ResourcesMap {
resp.ResourceTypes[name] = providers.Schema{
Version: int64(resource.SchemaVersion),
Block: resource.CoreConfigSchema(),
}
}
for name, data := range p.provider.DataSourcesMap {
resp.DataSources[name] = providers.Schema{
Version: int64(data.SchemaVersion),
Block: data.CoreConfigSchema(),
}
}
p.schemas = resp
return resp
}
// PrepareProviderConfig implements the PrepareProviderConfig from
// providers.Interface. Allows the provider to validate the configuration
// values, and set or override any values with defaults.
func (p *Provider) PrepareProviderConfig(req providers.PrepareProviderConfigRequest) (resp providers.PrepareProviderConfigResponse) {
// lookup any required, top-level attributes that are Null, and see if we
// have a Default value available.
configVal, err := cty.Transform(req.Config, func(path cty.Path, val cty.Value) (cty.Value, error) {
// we're only looking for top-level attributes
if len(path) != 1 {
return val, nil
}
// nothing to do if we already have a value
if !val.IsNull() {
return val, nil
}
// get the Schema definition for this attribute
getAttr, ok := path[0].(cty.GetAttrStep)
// these should all exist, but just ignore anything strange
if !ok {
return val, nil
}
attrSchema := p.provider.Schema[getAttr.Name]
// continue to ignore anything that doesn't match
if attrSchema == nil {
return val, nil
}
// this is deprecated, so don't set it
if attrSchema.Deprecated != "" || attrSchema.Removed != "" {
return val, nil
}
// find a default value if it exists
def, err := attrSchema.DefaultValue()
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(fmt.Errorf("error getting default for %q: %s", getAttr.Name, err))
return val, err
}
// no default
if def == nil {
return val, nil
}
// create a cty.Value and make sure it's the correct type
tmpVal := hcl2shim.HCL2ValueFromConfigValue(def)
// helper/schema used to allow setting "" to a bool
if val.Type() == cty.Bool && tmpVal.RawEquals(cty.StringVal("")) {
// return a warning about the conversion
resp.Diagnostics = resp.Diagnostics.Append("provider set empty string as default value for bool " + getAttr.Name)
tmpVal = cty.False
}
val, err = convert.Convert(tmpVal, val.Type())
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(fmt.Errorf("error setting default for %q: %s", getAttr.Name, err))
}
return val, err
})
if err != nil {
// any error here was already added to the diagnostics
return resp
}
schema := p.getSchema()
configVal, err = schema.Provider.Block.CoerceValue(configVal)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// Ensure there are no nulls that will cause helper/schema to panic.
if err := validateConfigNulls(configVal, nil); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
resp.PreparedConfig = configVal
return resp
}
// ValidateResourceTypeConfig implements the ValidateResourceTypeConfig from
// providers.Interface. Allows the provider to validate the resource
// configuration values.
func (p *Provider) ValidateResourceTypeConfig(req providers.ValidateResourceTypeConfigRequest) (resp providers.ValidateResourceTypeConfigResponse) {
schemaBlock := p.getResourceSchemaBlock(req.TypeName)
config := terraform.NewResourceConfigShimmed(req.Config, schemaBlock)
warns, errs := p.provider.ValidateResource(req.TypeName, config)
resp.Diagnostics = appendWarnsAndErrsToDiags(warns, errs)
return resp
}
// ValidateDataSourceConfig implements the ValidateDataSourceConfig from providers.Interface.
// Allows the provider to validate the data source configuration values.
func (p *Provider) ValidateDataSourceConfig(req providers.ValidateDataSourceConfigRequest) (resp providers.ValidateDataSourceConfigResponse) {
// Ensure there are no nulls that will cause helper/schema to panic.
if err := validateConfigNulls(req.Config, nil); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
schemaBlock := p.getDatasourceSchemaBlock(req.TypeName)
config := terraform.NewResourceConfigShimmed(req.Config, schemaBlock)
warns, errs := p.provider.ValidateDataSource(req.TypeName, config)
resp.Diagnostics = appendWarnsAndErrsToDiags(warns, errs)
return resp
}
// UpgradeResourceState implements the UpgradeResourceState from providers.Interface.
// It is called when the state loader encounters an instance state whose schema
// version is less than the one reported by the currently-used version of the
// corresponding provider, and the upgraded result is used for any further processing.
func (p *Provider) UpgradeResourceState(req providers.UpgradeResourceStateRequest) (resp providers.UpgradeResourceStateResponse) {
res := p.provider.ResourcesMap[req.TypeName]
schemaBlock := p.getResourceSchemaBlock(req.TypeName)
version := int(req.Version)
jsonMap := map[string]interface{}{}
var err error
switch {
// We first need to upgrade a flatmap state if it exists.
// There should never be both a JSON and Flatmap state in the request.
case len(req.RawStateFlatmap) > 0:
jsonMap, version, err = p.upgradeFlatmapState(version, req.RawStateFlatmap, res)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// if there's a JSON state, we need to decode it.
case len(req.RawStateJSON) > 0:
err = json.Unmarshal(req.RawStateJSON, &jsonMap)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
default:
// log.Println("[DEBUG] no state provided to upgrade")
return resp
}
// complete the upgrade of the JSON states
jsonMap, err = p.upgradeJSONState(version, jsonMap, res)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// The provider isn't required to clean out removed fields
p.removeAttributes(jsonMap, schemaBlock.ImpliedType())
// now we need to turn the state into the default json representation, so
// that it can be re-decoded using the actual schema.
val, err := schema.JSONMapToStateValue(jsonMap, schemaBlock)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// Now we need to make sure blocks are represented correctly, which means
// that missing blocks are empty collections, rather than null.
// First we need to CoerceValue to ensure that all object types match.
val, err = schemaBlock.CoerceValue(val)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// Normalize the value and fill in any missing blocks.
val = objchange.NormalizeObjectFromLegacySDK(val, schemaBlock)
resp.UpgradedState = val
return resp
}
// Configure implements the Configure from providers.Interface. Configures and
// initialized the provider.
func (p *Provider) Configure(req providers.ConfigureRequest) (resp providers.ConfigureResponse) {
p.provider.TerraformVersion = req.TerraformVersion
// Ensure there are no nulls that will cause helper/schema to panic.
if err := validateConfigNulls(req.Config, nil); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
schemaBlock := schema.InternalMap(p.provider.Schema).CoreConfigSchema()
config := terraform.NewResourceConfigShimmed(req.Config, schemaBlock)
err := p.provider.Configure(config)
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// Stop implements the Stop from providers.Interface. It is called when the
// provider should halt any in-flight actions.
//
// Stop should not block waiting for in-flight actions to complete. It
// should take any action it wants and return immediately acknowledging it
// has received the stop request. Terraform will not make any further API
// calls to the provider after Stop is called.
//
// The error returned, if non-nil, is assumed to mean that signaling the
// stop somehow failed and that the user should expect potentially waiting
// a longer period of time.
func (p *Provider) Stop() error {
return p.provider.Stop()
}
// ReadResource implements the ReadResource from providers.Interface. Refreshes
// a resource and returns its current state.
func (p *Provider) ReadResource(req providers.ReadResourceRequest) (resp providers.ReadResourceResponse) {
res := p.provider.ResourcesMap[req.TypeName]
schemaBlock := p.getResourceSchemaBlock(req.TypeName)
stateVal := req.PriorState
instanceState, err := res.ShimInstanceStateFromValue(stateVal)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
resp.Private = req.Private
private := make(map[string]interface{})
if len(req.Private) > 0 {
if err := json.Unmarshal(req.Private, &private); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
}
instanceState.Meta = private
newInstanceState, err := res.RefreshWithoutUpgrade(instanceState, p.provider.Meta())
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
if newInstanceState == nil || newInstanceState.ID == "" {
newStateVal := cty.NullVal(schemaBlock.ImpliedType())
resp.NewState = newStateVal
return resp
}
// helper/schema should always copy the ID over, but do it again just to be safe
newInstanceState.Attributes["id"] = newInstanceState.ID
newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(newInstanceState.Attributes, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
newStateVal = normalizeNullValues(newStateVal, stateVal, false)
newStateVal = copyTimeoutValues(newStateVal, stateVal)
resp.NewState = newStateVal
return resp
}
// PlanResourceChange implements the PlanResourceChange from providers.Interface.
// Takes the current state and proposed state of a resource, and returns the
// planned final state.
func (p *Provider) PlanResourceChange(req providers.PlanResourceChangeRequest) (resp providers.PlanResourceChangeResponse) {
// This is a signal to Terraform Core that we're doing the best we can to
// shim the legacy type system of the SDK onto the Terraform type system
// but we need it to cut us some slack. This setting should not be taken
// forward to any new SDK implementations, since setting it prevents us
// from catching certain classes of provider bug that can lead to
// confusing downstream errors.
resp.LegacyTypeSystem = true
res := p.provider.ResourcesMap[req.TypeName]
schemaBlock := p.getResourceSchemaBlock(req.TypeName)
priorStateVal := req.PriorState
create := priorStateVal.IsNull()
proposedNewStateVal := req.ProposedNewState
// We don't usually plan destroys, but this can return early in any case.
if proposedNewStateVal.IsNull() {
resp.PlannedState = req.ProposedNewState
resp.PlannedPrivate = req.PriorPrivate
return resp
}
info := &terraform.InstanceInfo{
Type: req.TypeName,
}
priorState, err := res.ShimInstanceStateFromValue(priorStateVal)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
priorPrivate := make(map[string]interface{})
if len(req.PriorPrivate) > 0 {
if err := json.Unmarshal(req.PriorPrivate, &priorPrivate); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
}
priorState.Meta = priorPrivate
// Ensure there are no nulls that will cause helper/schema to panic.
if err := validateConfigNulls(proposedNewStateVal, nil); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// turn the proposed state into a legacy configuration
cfg := terraform.NewResourceConfigShimmed(proposedNewStateVal, schemaBlock)
diff, err := p.provider.SimpleDiff(info, priorState, cfg)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// if this is a new instance, we need to make sure ID is going to be computed
if create {
if diff == nil {
diff = terraform.NewInstanceDiff()
}
diff.Attributes["id"] = &terraform.ResourceAttrDiff{
NewComputed: true,
}
}
if diff == nil || len(diff.Attributes) == 0 {
// schema.Provider.Diff returns nil if it ends up making a diff with no
// changes, but our new interface wants us to return an actual change
// description that _shows_ there are no changes. This is always the
// prior state, because we force a diff above if this is a new instance.
resp.PlannedState = req.PriorState
resp.PlannedPrivate = req.PriorPrivate
return resp
}
if priorState == nil {
priorState = &terraform.InstanceState{}
}
// now we need to apply the diff to the prior state, so get the planned state
plannedAttrs, err := diff.Apply(priorState.Attributes, schemaBlock)
plannedStateVal, err := hcl2shim.HCL2ValueFromFlatmap(plannedAttrs, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
plannedStateVal, err = schemaBlock.CoerceValue(plannedStateVal)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
plannedStateVal = normalizeNullValues(plannedStateVal, proposedNewStateVal, false)
plannedStateVal = copyTimeoutValues(plannedStateVal, proposedNewStateVal)
// The old SDK code has some imprecisions that cause it to sometimes
// generate differences that the SDK itself does not consider significant
// but Terraform Core would. To avoid producing weird do-nothing diffs
// in that case, we'll check if the provider as produced something we
// think is "equivalent" to the prior state and just return the prior state
// itself if so, thus ensuring that Terraform Core will treat this as
// a no-op. See the docs for ValuesSDKEquivalent for some caveats on its
// accuracy.
forceNoChanges := false
if hcl2shim.ValuesSDKEquivalent(priorStateVal, plannedStateVal) {
plannedStateVal = priorStateVal
forceNoChanges = true
}
// if this was creating the resource, we need to set any remaining computed
// fields
if create {
plannedStateVal = setUnknowns(plannedStateVal, schemaBlock)
}
resp.PlannedState = plannedStateVal
// encode any timeouts into the diff Meta
t := &schema.ResourceTimeout{}
if err := t.ConfigDecode(res, cfg); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
if err := t.DiffEncode(diff); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// Now we need to store any NewExtra values, which are where any actual
// StateFunc modified config fields are hidden.
privateMap := diff.Meta
if privateMap == nil {
privateMap = map[string]interface{}{}
}
newExtra := map[string]interface{}{}
for k, v := range diff.Attributes {
if v.NewExtra != nil {
newExtra[k] = v.NewExtra
}
}
privateMap[newExtraKey] = newExtra
// the Meta field gets encoded into PlannedPrivate
plannedPrivate, err := json.Marshal(privateMap)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
resp.PlannedPrivate = plannedPrivate
// collect the attributes that require instance replacement, and convert
// them to cty.Paths.
var requiresNew []string
if !forceNoChanges {
for attr, d := range diff.Attributes {
if d.RequiresNew {
requiresNew = append(requiresNew, attr)
}
}
}
// If anything requires a new resource already, or the "id" field indicates
// that we will be creating a new resource, then we need to add that to
// RequiresReplace so that core can tell if the instance is being replaced
// even if changes are being suppressed via "ignore_changes".
id := plannedStateVal.GetAttr("id")
if len(requiresNew) > 0 || id.IsNull() || !id.IsKnown() {
requiresNew = append(requiresNew, "id")
}
requiresReplace, err := hcl2shim.RequiresReplace(requiresNew, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// convert these to the protocol structures
for _, p := range requiresReplace {
resp.RequiresReplace = append(resp.RequiresReplace, p)
}
return resp
}
// ApplyResourceChange implements the ApplyResourceChange from providers.Interface.
// Takes the planned state for a resource, which may yet contain unknown computed
// values, and applies the changes returning the final state.
func (p *Provider) ApplyResourceChange(req providers.ApplyResourceChangeRequest) (resp providers.ApplyResourceChangeResponse) {
resp.NewState = req.PriorState
res := p.provider.ResourcesMap[req.TypeName]
schemaBlock := p.getResourceSchemaBlock(req.TypeName)
priorStateVal := req.PriorState
plannedStateVal := req.PlannedState
info := &terraform.InstanceInfo{
Type: req.TypeName,
}
priorState, err := res.ShimInstanceStateFromValue(priorStateVal)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
private := make(map[string]interface{})
if len(req.PlannedPrivate) > 0 {
if err := json.Unmarshal(req.PlannedPrivate, &private); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
}
var diff *terraform.InstanceDiff
destroy := false
// a null state means we are destroying the instance
if plannedStateVal.IsNull() {
destroy = true
diff = &terraform.InstanceDiff{
Attributes: make(map[string]*terraform.ResourceAttrDiff),
Meta: make(map[string]interface{}),
Destroy: true,
}
} else {
diff, err = schema.DiffFromValues(priorStateVal, plannedStateVal, stripResourceModifiers(res))
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
}
if diff == nil {
diff = &terraform.InstanceDiff{
Attributes: make(map[string]*terraform.ResourceAttrDiff),
Meta: make(map[string]interface{}),
}
}
// add NewExtra Fields that may have been stored in the private data
if newExtra := private[newExtraKey]; newExtra != nil {
for k, v := range newExtra.(map[string]interface{}) {
d := diff.Attributes[k]
if d == nil {
d = &terraform.ResourceAttrDiff{}
}
d.NewExtra = v
diff.Attributes[k] = d
}
}
if private != nil {
diff.Meta = private
}
for k, d := range diff.Attributes {
// We need to turn off any RequiresNew. There could be attributes
// without changes in here inserted by helper/schema, but if they have
// RequiresNew then the state will be dropped from the ResourceData.
d.RequiresNew = false
// Check that any "removed" attributes that don't actually exist in the
// prior state, or helper/schema will confuse itself
if d.NewRemoved {
if _, ok := priorState.Attributes[k]; !ok {
delete(diff.Attributes, k)
}
}
}
newInstanceState, err := p.provider.Apply(info, priorState, diff)
// we record the error here, but continue processing any returned state.
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
}
newStateVal := cty.NullVal(schemaBlock.ImpliedType())
// Always return a null value for destroy.
// While this is usually indicated by a nil state, check for missing ID or
// attributes in the case of a provider failure.
if destroy || newInstanceState == nil || newInstanceState.Attributes == nil || newInstanceState.ID == "" {
resp.NewState = newStateVal
return resp
}
// We keep the null val if we destroyed the resource, otherwise build the
// entire object, even if the new state was nil.
newStateVal, err = schema.StateValueFromInstanceState(newInstanceState, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
newStateVal = normalizeNullValues(newStateVal, plannedStateVal, true)
newStateVal = copyTimeoutValues(newStateVal, plannedStateVal)
resp.NewState = newStateVal
meta, err := json.Marshal(newInstanceState.Meta)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
resp.Private = meta
// This is a signal to Terraform Core that we're doing the best we can to
// shim the legacy type system of the SDK onto the Terraform type system
// but we need it to cut us some slack. This setting should not be taken
// forward to any new SDK implementations, since setting it prevents us
// from catching certain classes of provider bug that can lead to
// confusing downstream errors.
resp.LegacyTypeSystem = true
return resp
}
// ImportResourceState implements the ImportResourceState from providers.Interface.
// Requests that the given resource be imported.
func (p *Provider) ImportResourceState(req providers.ImportResourceStateRequest) (resp providers.ImportResourceStateResponse) {
info := &terraform.InstanceInfo{
Type: req.TypeName,
}
newInstanceStates, err := p.provider.ImportState(info, req.ID)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
for _, is := range newInstanceStates {
// copy the ID again just to be sure it wasn't missed
is.Attributes["id"] = is.ID
resourceType := is.Ephemeral.Type
if resourceType == "" {
resourceType = req.TypeName
}
schemaBlock := p.getResourceSchemaBlock(resourceType)
newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(is.Attributes, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// Normalize the value and fill in any missing blocks.
newStateVal = objchange.NormalizeObjectFromLegacySDK(newStateVal, schemaBlock)
meta, err := json.Marshal(is.Meta)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
resource := providers.ImportedResource{
TypeName: resourceType,
Private: meta,
State: newStateVal,
}
resp.ImportedResources = append(resp.ImportedResources, resource)
}
return resp
}
// ReadDataSource implements the ReadDataSource from providers.Interface.
// Returns the data source's current state.
func (p *Provider) ReadDataSource(req providers.ReadDataSourceRequest) (resp providers.ReadDataSourceResponse) {
// Ensure there are no nulls that will cause helper/schema to panic.
if err := validateConfigNulls(req.Config, nil); err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
schemaBlock := p.getDatasourceSchemaBlock(req.TypeName)
config := terraform.NewResourceConfigShimmed(req.Config, schemaBlock)
info := &terraform.InstanceInfo{
Type: req.TypeName,
}
// we need to still build the diff separately with the Read method to match
// the old behavior
diff, err := p.provider.ReadDataDiff(info, config)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
// now we can get the new complete data source
newInstanceState, err := p.provider.ReadDataApply(info, diff)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
newStateVal, err := schema.StateValueFromInstanceState(newInstanceState, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
newStateVal = copyTimeoutValues(newStateVal, req.Config)
resp.State = newStateVal
return resp
}
// Close implements the Close from providers.Interface. It's to shuts down the
// plugin process but this is not a plugin, so nothing is done here
func (p *Provider) Close() error {
return nil
}
// Internal methods
// =============================================================================
// getSchema is used internally to get the saved provider schema. The schema
// should have already been fetched from the provider, but we have to
// synchronize access to avoid being called concurrently with GetSchema.
func (p *Provider) getSchema() providers.GetSchemaResponse {
p.mu.Lock()
// unlock inline in case GetSchema needs to be called
if p.schemas.Provider.Block != nil {
p.mu.Unlock()
return p.schemas
}
p.mu.Unlock()
schemas := p.GetSchema()
if schemas.Diagnostics.HasErrors() {
panic(schemas.Diagnostics.Err())
}
return schemas
}
// validateConfigNulls checks a config value for unsupported nulls before
// attempting to shim the value. While null values can mostly be ignored in the
// configuration, since they're not supported in HCL1, the case where a null
// appears in a list-like attribute (list, set, tuple) will present a nil value
// to helper/schema which can panic. Return an error to the user in this case,
// indicating the attribute with the null value.
func validateConfigNulls(v cty.Value, path cty.Path) []tfdiags.Diagnostic {
var diags []tfdiags.Diagnostic
if v.IsNull() || !v.IsKnown() {
return diags
}
switch {
case v.Type().IsListType() || v.Type().IsSetType() || v.Type().IsTupleType():
it := v.ElementIterator()
for it.Next() {
kv, ev := it.Element()
if ev.IsNull() {
// if this is a set, the kv is also going to be null which
// isn't a valid path element, so we can't append it to the
// diagnostic.
p := path
if !kv.IsNull() {
p = append(p, cty.IndexStep{Key: kv})
}
newDiag := tfdiags.AttributeValue(
tfdiags.Error,
"Null value found in list",
"Null values are not allowed for this attribute value.",
p,
)
diags = append(diags, newDiag)
continue
}
d := validateConfigNulls(ev, append(path, cty.IndexStep{Key: kv}))
diags = append(diags, d...)
}
case v.Type().IsMapType() || v.Type().IsObjectType():
it := v.ElementIterator()
for it.Next() {
kv, ev := it.Element()
var step cty.PathStep
switch {
case v.Type().IsMapType():
step = cty.IndexStep{Key: kv}
case v.Type().IsObjectType():
step = cty.GetAttrStep{Name: kv.AsString()}
}
d := validateConfigNulls(ev, append(path, step))
diags = append(diags, d...)
}
}
return diags
}
func (p *Provider) getResourceSchemaBlock(name string) *configschema.Block {
res := p.provider.ResourcesMap[name]
return res.CoreConfigSchema()
}
func appendWarnsAndErrsToDiags(warns []string, errs []error) (diags []tfdiags.Diagnostic) {
for _, w := range warns {
newDiag := tfdiags.WholeContainingBody(tfdiags.Warning, w, w)
diags = append(diags, newDiag)
}
for _, e := range errs {
newDiag := tfdiags.WholeContainingBody(tfdiags.Error, e.Error(), e.Error())
diags = append(diags, newDiag)
}
return diags
}
func (p *Provider) getDatasourceSchemaBlock(name string) *configschema.Block {
dat := p.provider.DataSourcesMap[name]
return dat.CoreConfigSchema()
}
// upgradeFlatmapState takes a legacy flatmap state, upgrades it using Migrate
// state if necessary, and converts it to the new JSON state format decoded as a
// map[string]interface{}.
// upgradeFlatmapState returns the json map along with the corresponding schema
// version.
func (p *Provider) upgradeFlatmapState(version int, m map[string]string, res *schema.Resource) (map[string]interface{}, int, error) {
// this will be the version we've upgraded so, defaulting to the given
// version in case no migration was called.
upgradedVersion := version
// first determine if we need to call the legacy MigrateState func
requiresMigrate := version < res.SchemaVersion
schemaType := res.CoreConfigSchema().ImpliedType()
// if there are any StateUpgraders, then we need to only compare
// against the first version there
if len(res.StateUpgraders) > 0 {
requiresMigrate = version < res.StateUpgraders[0].Version
}
if requiresMigrate && res.MigrateState == nil {
// Providers were previously allowed to bump the version
// without declaring MigrateState.
// If there are further upgraders, then we've only updated that far.
if len(res.StateUpgraders) > 0 {
schemaType = res.StateUpgraders[0].Type
upgradedVersion = res.StateUpgraders[0].Version
}
} else if requiresMigrate {
is := &terraform.InstanceState{
ID: m["id"],
Attributes: m,
Meta: map[string]interface{}{
"schema_version": strconv.Itoa(version),
},
}
is, err := res.MigrateState(version, is, p.provider.Meta())
if err != nil {
return nil, 0, err
}
// re-assign the map in case there was a copy made, making sure to keep
// the ID
m := is.Attributes
m["id"] = is.ID
// if there are further upgraders, then we've only updated that far
if len(res.StateUpgraders) > 0 {
schemaType = res.StateUpgraders[0].Type
upgradedVersion = res.StateUpgraders[0].Version
}
} else {
// the schema version may be newer than the MigrateState functions
// handled and older than the current, but still stored in the flatmap
// form. If that's the case, we need to find the correct schema type to
// convert the state.
for _, upgrader := range res.StateUpgraders {
if upgrader.Version == version {
schemaType = upgrader.Type
break
}
}
}
// now we know the state is up to the latest version that handled the
// flatmap format state. Now we can upgrade the format and continue from
// there.
newConfigVal, err := hcl2shim.HCL2ValueFromFlatmap(m, schemaType)
if err != nil {
return nil, 0, err
}
jsonMap, err := schema.StateValueToJSONMap(newConfigVal, schemaType)
return jsonMap, upgradedVersion, err
}
func (p *Provider) upgradeJSONState(version int, m map[string]interface{}, res *schema.Resource) (map[string]interface{}, error) {
var err error
for _, upgrader := range res.StateUpgraders {
if version != upgrader.Version {
continue
}