-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathazapi_resource.go
More file actions
1542 lines (1376 loc) · 60.2 KB
/
azapi_resource.go
File metadata and controls
1542 lines (1376 loc) · 60.2 KB
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 services
import (
"context"
"encoding/json"
"fmt"
"reflect"
"slices"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/terraform-provider-azapi/internal/azure"
"github.com/Azure/terraform-provider-azapi/internal/azure/identity"
"github.com/Azure/terraform-provider-azapi/internal/azure/location"
"github.com/Azure/terraform-provider-azapi/internal/azure/tags"
aztypes "github.com/Azure/terraform-provider-azapi/internal/azure/types"
"github.com/Azure/terraform-provider-azapi/internal/clients"
"github.com/Azure/terraform-provider-azapi/internal/docstrings"
"github.com/Azure/terraform-provider-azapi/internal/locks"
"github.com/Azure/terraform-provider-azapi/internal/retry"
"github.com/Azure/terraform-provider-azapi/internal/services/common"
"github.com/Azure/terraform-provider-azapi/internal/services/defaults"
"github.com/Azure/terraform-provider-azapi/internal/services/dynamic"
"github.com/Azure/terraform-provider-azapi/internal/services/migration"
"github.com/Azure/terraform-provider-azapi/internal/services/myplanmodifier"
"github.com/Azure/terraform-provider-azapi/internal/services/myplanmodifier/planmodifierdynamic"
"github.com/Azure/terraform-provider-azapi/internal/services/myvalidator"
"github.com/Azure/terraform-provider-azapi/internal/services/parse"
"github.com/Azure/terraform-provider-azapi/internal/services/preflight"
"github.com/Azure/terraform-provider-azapi/internal/skip"
"github.com/Azure/terraform-provider-azapi/internal/tf"
"github.com/Azure/terraform-provider-azapi/utils"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/identityschema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
)
const FlagMoveState = "move_state"
type AzapiResourceModel struct {
Body types.Dynamic `tfsdk:"body"`
SensitiveBody types.Dynamic `tfsdk:"sensitive_body"`
SensitiveBodyVersion types.Map `tfsdk:"sensitive_body_version"`
ID types.String `tfsdk:"id"`
Identity types.List `tfsdk:"identity"`
IgnoreCasing types.Bool `tfsdk:"ignore_casing"`
IgnoreMissingProperty types.Bool `tfsdk:"ignore_missing_property"`
IgnoreNullProperty types.Bool `tfsdk:"ignore_null_property"`
Location types.String `tfsdk:"location"`
Locks types.List `tfsdk:"locks"`
Name types.String `tfsdk:"name"`
Output types.Dynamic `tfsdk:"output"`
ParentID types.String `tfsdk:"parent_id"`
ReplaceTriggersExternalValues types.Dynamic `tfsdk:"replace_triggers_external_values"`
ReplaceTriggersRefs types.List `tfsdk:"replace_triggers_refs"`
ResponseExportValues types.Dynamic `tfsdk:"response_export_values"`
Retry retry.RetryValue `tfsdk:"retry" skip_on:"update"`
SchemaValidationEnabled types.Bool `tfsdk:"schema_validation_enabled"`
Tags types.Map `tfsdk:"tags"`
Timeouts timeouts.Value `tfsdk:"timeouts" skip_on:"update"`
Type types.String `tfsdk:"type"`
CreateHeaders types.Map `tfsdk:"create_headers" skip_on:"update"`
CreateQueryParameters types.Map `tfsdk:"create_query_parameters" skip_on:"update"`
UpdateHeaders types.Map `tfsdk:"update_headers"`
UpdateQueryParameters types.Map `tfsdk:"update_query_parameters"`
DeleteHeaders types.Map `tfsdk:"delete_headers" skip_on:"update"`
DeleteQueryParameters types.Map `tfsdk:"delete_query_parameters" skip_on:"update"`
ReadHeaders types.Map `tfsdk:"read_headers" skip_on:"update"`
ReadQueryParameters types.Map `tfsdk:"read_query_parameters" skip_on:"update"`
}
// AzapiResourceIdentityModel represents the identity data for importing a resource
type AzapiResourceIdentityModel struct {
ID types.String `tfsdk:"id"`
Type types.String `tfsdk:"type"`
}
func NewDefaultAzapiResourceModel() AzapiResourceModel {
return AzapiResourceModel{
ID: types.StringNull(),
Name: types.StringNull(),
ParentID: types.StringNull(),
Type: types.StringNull(),
Location: types.StringNull(),
Body: types.Dynamic{},
SensitiveBodyVersion: types.MapNull(types.StringType),
Identity: types.ListNull(identity.Model{}.ModelType()),
IgnoreCasing: types.BoolValue(false),
IgnoreMissingProperty: types.BoolValue(true),
IgnoreNullProperty: types.BoolValue(false),
Locks: types.ListNull(types.StringType),
Output: types.DynamicNull(),
ReplaceTriggersExternalValues: types.DynamicNull(),
ReplaceTriggersRefs: types.ListNull(types.StringType),
ResponseExportValues: types.DynamicNull(),
Retry: retry.RetryValue{},
SchemaValidationEnabled: types.BoolValue(true),
Tags: types.MapNull(types.StringType),
Timeouts: timeouts.Value{
Object: types.ObjectNull(map[string]attr.Type{
"create": types.StringType,
"update": types.StringType,
"read": types.StringType,
"delete": types.StringType,
}),
},
CreateHeaders: types.MapNull(types.StringType),
CreateQueryParameters: types.MapNull(types.ListType{ElemType: types.StringType}),
UpdateHeaders: types.MapNull(types.StringType),
UpdateQueryParameters: types.MapNull(types.ListType{ElemType: types.StringType}),
DeleteHeaders: types.MapNull(types.StringType),
DeleteQueryParameters: types.MapNull(types.ListType{ElemType: types.StringType}),
ReadHeaders: types.MapNull(types.StringType),
ReadQueryParameters: types.MapNull(types.ListType{ElemType: types.StringType}),
}
}
var _ resource.Resource = &AzapiResource{}
var _ resource.ResourceWithConfigure = &AzapiResource{}
var _ resource.ResourceWithModifyPlan = &AzapiResource{}
var _ resource.ResourceWithValidateConfig = &AzapiResource{}
var _ resource.ResourceWithImportState = &AzapiResource{}
var _ resource.ResourceWithUpgradeState = &AzapiResource{}
var _ resource.ResourceWithMoveState = &AzapiResource{}
var _ resource.ResourceWithIdentity = &AzapiResource{}
type AzapiResource struct {
ProviderData *clients.Client
}
func (r *AzapiResource) Configure(ctx context.Context, request resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if v, ok := request.ProviderData.(*clients.Client); ok {
r.ProviderData = v
}
}
func (r *AzapiResource) Metadata(_ context.Context, request resource.MetadataRequest, response *resource.MetadataResponse) {
response.TypeName = request.ProviderTypeName + "_resource"
}
func (r *AzapiResource) UpgradeState(ctx context.Context) map[int64]resource.StateUpgrader {
return map[int64]resource.StateUpgrader{
0: migration.AzapiResourceMigrationV0ToV2(ctx),
1: migration.AzapiResourceMigrationV1ToV2(ctx),
}
}
func (r *AzapiResource) Schema(ctx context.Context, _ resource.SchemaRequest, response *resource.SchemaResponse) {
response.Schema = schema.Schema{
MarkdownDescription: "This resource can manage any Azure Resource Manager resource.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
MarkdownDescription: docstrings.ID(),
},
"name": schema.StringAttribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
MarkdownDescription: "Specifies the name of the azure resource. Changing this forces a new resource to be created.",
},
"parent_id": schema.StringAttribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
myvalidator.StringIsResourceID(),
},
MarkdownDescription: docstrings.ParentID(),
},
"type": schema.StringAttribute{
Required: true,
Validators: []validator.String{
myvalidator.StringIsResourceType(),
},
MarkdownDescription: docstrings.Type(),
},
"location": schema.StringAttribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
myplanmodifier.UseStateWhen(func(a, b types.String) bool {
return location.Normalize(a.ValueString()) == location.Normalize(b.ValueString())
}),
},
MarkdownDescription: docstrings.Location(),
},
// The body attribute is a dynamic attribute that only allows users to specify the resource body as an HCL object
"body": schema.DynamicAttribute{
Optional: true,
Computed: true,
// in the previous version, the default value is string "{}", now it's a dynamic value {}
Default: defaults.DynamicDefault(types.ObjectValueMust(map[string]attr.Type{}, map[string]attr.Value{})),
PlanModifiers: []planmodifier.Dynamic{
myplanmodifier.DynamicUseStateWhen(dynamic.SemanticallyEqual),
},
MarkdownDescription: docstrings.Body(),
Validators: []validator.Dynamic{
myvalidator.DynamicIsNotStringValidator(),
},
},
"sensitive_body": schema.DynamicAttribute{
Optional: true,
WriteOnly: true,
MarkdownDescription: docstrings.SensitiveBody(),
},
"sensitive_body_version": schema.MapAttribute{
ElementType: types.StringType,
Optional: true,
MarkdownDescription: docstrings.SensitiveBodyVersion(),
},
"replace_triggers_external_values": schema.DynamicAttribute{
Optional: true,
MarkdownDescription: "Will trigger a replace of the resource when the value changes and is not `null`. This can be used by practitioners to force a replace of the resource when certain values change, e.g. changing the SKU of a virtual machine based on the value of variables or locals. " +
"The value is a `dynamic`, so practitioners can compose the input however they wish. For a \"break glass\" set the value to `null` to prevent the plan modifier taking effect. \n" +
"If you have `null` values that you do want to be tracked as affecting the resource replacement, include these inside an object. \n" +
"Advanced use cases are possible and resource replacement can be triggered by values external to the resource, for example when a dependent resource changes.\n\n" +
"e.g. to replace a resource when either the SKU or os_type attributes change:\n" +
"\n" +
"```hcl\n" +
"resource \"azapi_resource\" \"example\" {\n" +
" name = var.name\n" +
" type = \"Microsoft.Network/publicIPAddresses@2023-11-01\"\n" +
" parent_id = \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example\"\n" +
" body = {\n" +
" properties = {\n" +
" sku = var.sku\n" +
" zones = var.zones\n" +
" }\n" +
" }\n" +
"\n" +
" replace_triggers_external_values = [\n" +
" var.sku,\n" +
" var.zones,\n" +
" ]\n" +
"}\n" +
"```\n",
PlanModifiers: []planmodifier.Dynamic{
planmodifierdynamic.RequiresReplaceIfNotNull(),
},
},
"replace_triggers_refs": schema.ListAttribute{
ElementType: types.StringType,
Optional: true,
MarkdownDescription: "A list of paths in the current Terraform configuration. When the values at these paths change, the resource will be replaced.",
},
"ignore_casing": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: defaults.BoolDefault(false),
MarkdownDescription: docstrings.IgnoreCasing(),
},
"ignore_missing_property": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: defaults.BoolDefault(true),
MarkdownDescription: docstrings.IgnoreMissingProperty(),
},
"ignore_null_property": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: defaults.BoolDefault(false),
MarkdownDescription: docstrings.IgnoreNullProperty(),
},
"response_export_values": schema.DynamicAttribute{
Optional: true,
PlanModifiers: []planmodifier.Dynamic{
myplanmodifier.DynamicUseStateWhen(dynamic.SemanticallyEqual),
},
MarkdownDescription: docstrings.ResponseExportValues(),
},
"locks": schema.ListAttribute{
ElementType: types.StringType,
Optional: true,
Validators: []validator.List{
listvalidator.ValueStringsAre(myvalidator.StringIsNotEmpty()),
},
MarkdownDescription: docstrings.Locks(),
},
"schema_validation_enabled": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: defaults.BoolDefault(true),
MarkdownDescription: docstrings.SchemaValidationEnabled(),
},
"output": schema.DynamicAttribute{
Computed: true,
MarkdownDescription: docstrings.Output("azapi_resource"),
},
"tags": schema.MapAttribute{
ElementType: types.StringType,
Optional: true,
Computed: true,
Validators: []validator.Map{
tags.Validator(),
},
MarkdownDescription: "A mapping of tags which should be assigned to the Azure resource.",
},
"retry": retry.RetrySchema(ctx),
"create_headers": schema.MapAttribute{
ElementType: types.StringType,
Optional: true,
MarkdownDescription: "A mapping of headers to be sent with the create request.",
},
"create_query_parameters": schema.MapAttribute{
ElementType: types.ListType{
ElemType: types.StringType,
},
Optional: true,
MarkdownDescription: "A mapping of query parameters to be sent with the create request.",
},
"update_headers": schema.MapAttribute{
ElementType: types.StringType,
Optional: true,
MarkdownDescription: "A mapping of headers to be sent with the update request.",
},
"update_query_parameters": schema.MapAttribute{
ElementType: types.ListType{
ElemType: types.StringType,
},
Optional: true,
MarkdownDescription: "A mapping of query parameters to be sent with the update request.",
},
"delete_headers": schema.MapAttribute{
ElementType: types.StringType,
Optional: true,
MarkdownDescription: "A mapping of headers to be sent with the delete request.",
},
"delete_query_parameters": schema.MapAttribute{
ElementType: types.ListType{
ElemType: types.StringType,
},
Optional: true,
MarkdownDescription: "A mapping of query parameters to be sent with the delete request.",
},
"read_headers": schema.MapAttribute{
ElementType: types.StringType,
Optional: true,
MarkdownDescription: "A mapping of headers to be sent with the read request.",
},
"read_query_parameters": schema.MapAttribute{
ElementType: types.ListType{
ElemType: types.StringType,
},
Optional: true,
MarkdownDescription: "A mapping of query parameters to be sent with the read request.",
},
},
Blocks: map[string]schema.Block{
"identity": schema.ListNestedBlock{
NestedObject: schema.NestedBlockObject{
Validators: []validator.Object{myvalidator.IdentityValidator()},
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
Required: true,
Validators: []validator.String{stringvalidator.OneOf(
string(identity.SystemAssignedUserAssigned),
string(identity.UserAssigned),
string(identity.SystemAssigned),
string(identity.None),
)},
MarkdownDescription: docstrings.IdentityType(),
},
"identity_ids": schema.ListAttribute{
ElementType: types.StringType,
Optional: true,
Validators: []validator.List{
listvalidator.ValueStringsAre(myvalidator.StringIsUserAssignedIdentityID()),
},
PlanModifiers: []planmodifier.List{
myplanmodifier.ListUseStateWhen(identity.IdentityIDsSemanticallyEqual),
},
MarkdownDescription: docstrings.IdentityIds(),
},
"principal_id": schema.StringAttribute{
Computed: true,
MarkdownDescription: docstrings.IdentityPrincipalID(),
},
"tenant_id": schema.StringAttribute{
Computed: true,
MarkdownDescription: docstrings.IdentityTenantID(),
},
},
},
},
"timeouts": timeouts.Block(ctx, timeouts.Opts{
Create: true,
Update: true,
Read: true,
Delete: true,
}),
},
Version: 2,
}
}
func (r *AzapiResource) IdentitySchema(ctx context.Context, request resource.IdentitySchemaRequest, response *resource.IdentitySchemaResponse) {
response.IdentitySchema = identityschema.Schema{
Attributes: map[string]identityschema.Attribute{
"id": identityschema.StringAttribute{
RequiredForImport: true,
Description: "The Azure resource ID",
},
"type": identityschema.StringAttribute{
OptionalForImport: true,
Description: "The Azure resource type",
},
},
Version: 0,
}
}
func (r *AzapiResource) ValidateConfig(ctx context.Context, request resource.ValidateConfigRequest, response *resource.ValidateConfigResponse) {
var config *AzapiResourceModel
if response.Diagnostics.Append(request.Config.Get(ctx, &config)...); response.Diagnostics.HasError() {
return
}
// destroy doesn't need to modify plan
if config == nil {
return
}
if config.Type.IsUnknown() {
return
}
resourceType := config.Type.ValueString()
// for resource group, if parent_id is not specified, set it to subscription id
if config.ParentID.IsNull() {
azureResourceType, _, _ := utils.GetAzureResourceTypeApiVersion(resourceType)
if !strings.EqualFold(azureResourceType, arm.ResourceGroupResourceType.String()) {
response.Diagnostics.AddError("Missing required argument", `The argument "parent_id" is required, but no definition was found.`)
return
}
}
if diags := validateDuplicatedDefinitions(config, config.Body, "body"); diags.HasError() {
response.Diagnostics.Append(diags...)
return
}
if diags := validateDuplicatedDefinitions(config, config.SensitiveBody, "sensitive_body"); diags.HasError() {
response.Diagnostics.Append(diags...)
return
}
if config.SchemaValidationEnabled.IsNull() || config.SchemaValidationEnabled.ValueBool() {
if err := schemaValidate(config); err != nil {
response.Diagnostics.AddError("Invalid configuration", err.Error())
return
}
}
}
func (r *AzapiResource) ModifyPlan(ctx context.Context, request resource.ModifyPlanRequest, response *resource.ModifyPlanResponse) {
var config, state, plan *AzapiResourceModel
response.Diagnostics.Append(request.Config.Get(ctx, &config)...)
response.Diagnostics.Append(request.State.Get(ctx, &state)...)
response.Diagnostics.Append(request.Plan.Get(ctx, &plan)...)
if response.Diagnostics.HasError() {
return
}
// destroy doesn't need to modify plan
if config == nil {
return
}
defer func() {
if plan.Output.IsUnknown() {
plan.Body = config.Body
plan.Type = config.Type
}
response.Plan.Set(ctx, plan)
}()
// Output is a computed field, it defaults to unknown if there's any plan change
// It sets to the state if the state exists, and will set to unknown if the output needs to be updated
if state != nil {
plan.Output = state.Output
}
azureResourceType, apiVersion, err := utils.GetAzureResourceTypeApiVersion(config.Type.ValueString())
if err != nil {
response.Diagnostics.AddError("Invalid configuration", fmt.Sprintf(`The argument "type" is invalid: %s`, err.Error()))
return
}
resourceDef, _ := azure.GetResourceDefinition(azureResourceType, apiVersion)
// for resource group, if parent_id is not specified, set it to subscription id
if config.ParentID.IsNull() && strings.EqualFold(azureResourceType, arm.ResourceGroupResourceType.String()) {
plan.ParentID = types.StringValue(fmt.Sprintf("/subscriptions/%s", r.ProviderData.Account.GetSubscriptionId()))
}
if name, diags := r.nameWithDefaultNaming(config.Name); !diags.HasError() {
plan.Name = name
// replace the resource if the name is changed
if state != nil && !state.Name.Equal(plan.Name) {
response.RequiresReplace.Append(path.Root("name"))
}
} else {
response.Diagnostics.Append(diags...)
return
}
// if the config identity type and identity ids are not changed, use the state identity
if !plan.Identity.IsNull() && state != nil && !state.Identity.IsNull() {
planIdentity := identity.FromList(plan.Identity)
stateIdentity := identity.FromList(state.Identity)
if planIdentity.Type.Equal(stateIdentity.Type) && planIdentity.IdentityIDs.Equal(stateIdentity.IdentityIDs) {
plan.Identity = state.Identity
}
}
// In the below two cases, we think the config is still matched with the remote state, and there's no need to update the resource:
// 1. If the api-version is changed, but the body is not changed
// 2. If the body only removes/adds properties that are equal to the remote state
if r.ProviderData.Features.IgnoreNoOpChanges && dynamic.IsFullyKnown(plan.Body) && state != nil && (!dynamic.SemanticallyEqual(plan.Body, state.Body) || !plan.Type.Equal(state.Type)) {
// GET the existing resource with config's api-version
responseBody, err := r.ProviderData.ResourceClient.Get(ctx, state.ID.ValueString(), apiVersion, clients.DefaultRequestOptions())
if err != nil {
response.Diagnostics.AddError("Failed to retrieve resource", fmt.Sprintf("Retrieving existing resource %s: %+v", state.ID.ValueString(), err))
return
}
stateBody := make(map[string]interface{})
if err := unmarshalBody(state.Body, &stateBody); err != nil {
response.Diagnostics.AddError("Invalid state body", fmt.Sprintf(`The argument "body" in state is invalid: %s`, err.Error()))
return
}
// stateBody contains sensitive properties that are not returned in GET response
responseBody = utils.MergeObject(responseBody, stateBody)
configBody := make(map[string]interface{})
if err := unmarshalBody(plan.Body, &configBody); err != nil {
response.Diagnostics.AddError("Invalid body", fmt.Sprintf(`The argument "body" is invalid: %s`, err.Error()))
return
}
option := utils.UpdateJsonOption{
IgnoreCasing: plan.IgnoreCasing.ValueBool(),
IgnoreMissingProperty: false,
IgnoreNullProperty: plan.IgnoreNullProperty.ValueBool(),
}
remoteBody := utils.UpdateObject(configBody, responseBody, option)
// suppress the change if the remote body is equal to the config body
if reflect.DeepEqual(remoteBody, configBody) {
plan.Body = state.Body
plan.Type = state.Type
}
}
isNewResource := state == nil
if !dynamic.IsFullyKnown(plan.Body) || isNewResource || !plan.Identity.Equal(state.Identity) ||
!plan.Type.Equal(state.Type) ||
!plan.ResponseExportValues.Equal(state.ResponseExportValues) || !dynamic.SemanticallyEqual(plan.Body, state.Body) {
plan.Output = basetypes.NewDynamicUnknown()
}
if !dynamic.IsFullyKnown(plan.Body) {
if config.Tags.IsNull() {
plan.Tags = basetypes.NewMapUnknown(types.StringType)
}
if config.Location.IsNull() {
plan.Location = basetypes.NewStringUnknown()
}
}
if state != nil {
// Set output as unknown to trigger a plan diff, if ephemral body has changed
diff, diags := ephemeralBodyChangeInPlan(ctx, request.Private, config.SensitiveBody, config.SensitiveBodyVersion, state.SensitiveBodyVersion)
if response.Diagnostics = append(response.Diagnostics, diags...); response.Diagnostics.HasError() {
return
}
if diff {
tflog.Info(ctx, `"sensitive_body" has changed`)
plan.Output = types.DynamicUnknown()
}
}
if dynamic.IsFullyKnown(plan.Body) {
plan.Tags = r.tagsWithDefaultTags(config.Tags, state, config.Body, resourceDef)
if state == nil || !state.Tags.Equal(plan.Tags) {
plan.Output = basetypes.NewDynamicUnknown()
}
// locationWithDefaultLocation will return the location in config if it's not null, otherwise it will return the default location if it supports location
plan.Location = r.locationWithDefaultLocation(config.Location, plan.Location, state, config.Body, resourceDef)
if state != nil && location.Normalize(state.Location.ValueString()) != location.Normalize(plan.Location.ValueString()) {
// if the location is changed, replace the resource
response.RequiresReplace.Append(path.Root("location"))
}
// Check if any paths in replace_triggers_refs have changed
if state != nil && plan != nil && !plan.ReplaceTriggersRefs.IsNull() {
refPaths := make(map[string]string)
for pathIndex, refPath := range common.AsStringList(plan.ReplaceTriggersRefs) {
refPaths[fmt.Sprintf("%d", pathIndex)] = refPath
}
// read previous values from state
stateData, err := dynamic.ToJSON(state.Body)
if err != nil {
response.Diagnostics.AddError("Invalid state body configuration", err.Error())
return
}
var stateModel interface{}
err = json.Unmarshal(stateData, &stateModel)
if err != nil {
response.Diagnostics.AddError("Invalid state body configuration", err.Error())
return
}
previousValues := flattenOutputJMES(stateModel, refPaths)
// read current values from plan
planData, err := dynamic.ToJSON(plan.Body)
if err != nil {
response.Diagnostics.AddError("Invalid plan body configuration", err.Error())
return
}
var planModel interface{}
err = json.Unmarshal(planData, &planModel)
if err != nil {
response.Diagnostics.AddError("Invalid plan body configuration", err.Error())
return
}
currentValues := flattenOutputJMES(planModel, refPaths)
// compare previous and current values
if !reflect.DeepEqual(previousValues, currentValues) {
response.RequiresReplace.Append(path.Root("body"))
}
}
}
if r.ProviderData.Features.EnablePreflight && isNewResource {
parentId := plan.ParentID.ValueString()
if parentId == "" {
placeholder, err := preflight.ParentIdPlaceholder(resourceDef, r.ProviderData.Account.GetSubscriptionId())
if err != nil {
return
}
parentId = placeholder
}
name := plan.Name.ValueString()
if name == "" {
name = preflight.NamePlaceholder()
}
err = preflight.Validate(ctx, r.ProviderData.ResourceClient, plan.Type.ValueString(), parentId, name, plan.Location.ValueString(), plan.Body, plan.Identity)
if err != nil {
response.Diagnostics.AddError("Preflight Validation: Invalid configuration", err.Error())
return
}
}
}
func (r *AzapiResource) Create(ctx context.Context, request resource.CreateRequest, response *resource.CreateResponse) {
r.CreateUpdate(ctx, request.Config, request.Plan, &response.State, &response.Diagnostics, response.Private)
var model *AzapiResourceModel
if response.Diagnostics.Append(response.State.Get(ctx, &model)...); !response.Diagnostics.HasError() && model != nil && !model.ID.IsNull() {
response.Diagnostics.Append(response.Identity.SetAttribute(ctx, path.Root("id"), model.ID)...)
}
}
func (r *AzapiResource) Update(ctx context.Context, request resource.UpdateRequest, response *resource.UpdateResponse) {
// See if we can skip the external API call (changes are to state only)
var plan, state AzapiResourceModel
if response.Diagnostics.Append(request.Plan.Get(ctx, &plan)...); response.Diagnostics.HasError() {
return
}
if response.Diagnostics.Append(request.State.Get(ctx, &state)...); response.Diagnostics.HasError() {
return
}
// This is a workaround for the issue: https://github.com/Azure/terraform-provider-azapi/issues/1023
// The issue is that the identity is not set in the response when the resource is updated.
// This issue only happens when the terraform version is below 1.12.
if !state.ID.IsNull() {
response.Diagnostics.Append(response.Identity.SetAttribute(ctx, path.Root("id"), state.ID)...)
}
if skip.CanSkipExternalRequest(plan, state, "update") {
response.Diagnostics.Append(response.State.Set(ctx, plan)...)
tflog.Debug(ctx, "azapi_resource.CreateUpdate skipping external request as no unskippable changes were detected")
return
}
tflog.Debug(ctx, "azapi_resource.CreateUpdate proceeding with external request as no skippable changes were detected")
r.CreateUpdate(ctx, request.Config, request.Plan, &response.State, &response.Diagnostics, response.Private)
}
func (r *AzapiResource) CreateUpdate(ctx context.Context, requestConfig tfsdk.Config, requestPlan tfsdk.Plan, responseState *tfsdk.State, diagnostics *diag.Diagnostics, privateData PrivateData) {
var config, plan, state *AzapiResourceModel
diagnostics.Append(requestConfig.Get(ctx, &config)...)
diagnostics.Append(requestPlan.Get(ctx, &plan)...)
diagnostics.Append(responseState.Get(ctx, &state)...)
if diagnostics.HasError() {
return
}
id, err := parse.NewResourceID(plan.Name.ValueString(), plan.ParentID.ValueString(), plan.Type.ValueString())
if err != nil {
diagnostics.AddError("Invalid configuration", err.Error())
return
}
ctx = tflog.SetField(ctx, "resource_id", id.ID())
isNewResource := responseState == nil || responseState.Raw.IsNull()
ctx = tflog.SetField(ctx, "is_new_resource", isNewResource)
var timeout time.Duration
var diags diag.Diagnostics
if isNewResource {
timeout, diags = plan.Timeouts.Create(ctx, 30*time.Minute)
if diagnostics.Append(diags...); diagnostics.HasError() {
return
}
} else {
timeout, diags = plan.Timeouts.Update(ctx, 30*time.Minute)
if diagnostics.Append(diags...); diagnostics.HasError() {
return
}
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
client := r.ProviderData.ResourceClient
if isNewResource {
// check if the resource already exists using the non-retry client to avoid issue where user specifies
// a FooResourceNotFound error as a retryable error
requestOptions := clients.RequestOptions{
Headers: common.AsMapOfString(plan.ReadHeaders),
QueryParameters: clients.NewQueryParameters(common.AsMapOfLists(plan.ReadQueryParameters)),
}
_, err = client.Get(ctx, id.AzureResourceId, id.ApiVersion, requestOptions)
if err == nil {
diagnostics.AddError("Resource already exists", tf.ImportAsExistsError("azapi_resource", id.ID()).Error())
return
}
// 403 is returned if group (or child resource of group) does not exist, bug tracked at: https://github.com/Azure/azure-rest-api-specs/issues/9549
if !utils.ResponseErrorWasNotFound(err) && !(utils.ResponseWasForbidden(err) && isManagementGroupScope(id.ID())) {
diagnostics.AddError("Failed to retrieve resource", fmt.Errorf("checking for presence of existing %s: %+v", id, err).Error())
return
}
}
// build the request body
body := make(map[string]interface{})
if err := unmarshalBody(plan.Body, &body); err != nil {
diagnostics.AddError("Invalid body", fmt.Sprintf(`The argument "body" is invalid: %s`, err.Error()))
return
}
if diagnostics.Append(expandBody(body, *plan)...); diagnostics.HasError() {
return
}
sensitiveBodyVersionInState := types.MapNull(types.StringType)
if state != nil {
sensitiveBodyVersionInState = state.SensitiveBodyVersion
}
sensitiveBody, err := unmarshalSensitiveBody(config.SensitiveBody, plan.SensitiveBodyVersion, sensitiveBodyVersionInState)
if err != nil {
diagnostics.AddError("Invalid sensitive_body", fmt.Sprintf(`The argument "sensitive_body" is invalid: %s`, err.Error()))
return
}
if sensitiveBody != nil {
body = utils.MergeObject(body, sensitiveBody).(map[string]interface{})
}
if !isNewResource {
// handle the case that identity block was once set, now it's removed
if stateIdentity := identity.FromList(state.Identity); body["identity"] == nil && stateIdentity.Type.ValueString() != string(identity.None) {
noneIdentity := identity.Model{Type: types.StringValue(string(identity.None))}
out, _ := identity.ExpandIdentity(noneIdentity)
body["identity"] = out
}
}
if plan.IgnoreNullProperty.ValueBool() {
out := utils.RemoveNullProperty(body)
v, ok := out.(map[string]interface{})
if ok {
body = v
}
}
// create/update the resource
lockIds := common.AsStringList(plan.Locks)
slices.Sort(lockIds)
for _, lockId := range lockIds {
locks.ByID(lockId)
defer locks.UnlockByID(lockId)
}
requestOptions := clients.RequestOptions{
Headers: common.AsMapOfString(plan.CreateHeaders),
QueryParameters: clients.NewQueryParameters(common.AsMapOfLists(plan.CreateQueryParameters)),
RetryOptions: clients.NewRetryOptions(plan.Retry),
}
if !isNewResource {
requestOptions.Headers = common.AsMapOfString(plan.UpdateHeaders)
requestOptions.QueryParameters = clients.NewQueryParameters(common.AsMapOfLists(plan.UpdateQueryParameters))
}
_, err = client.CreateOrUpdate(ctx, id.AzureResourceId, id.ApiVersion, body, requestOptions)
if err != nil {
tflog.Debug(ctx, "azapi_resource.CreateUpdate client call create/update resource failed", map[string]interface{}{
"err": err,
})
if isNewResource {
requestOptions := clients.RequestOptions{
Headers: common.AsMapOfString(plan.ReadHeaders),
QueryParameters: clients.NewQueryParameters(common.AsMapOfLists(plan.ReadQueryParameters)),
RetryOptions: clients.NewRetryOptions(plan.Retry),
}
if responseBody, err := client.Get(ctx, id.AzureResourceId, id.ApiVersion, requestOptions); err == nil {
// generate the computed fields
plan.ID = types.StringValue(id.ID())
var defaultOutput interface{}
if !r.ProviderData.Features.DisableDefaultOutput {
defaultOutput = id.ResourceDef.GetReadOnly(responseBody)
defaultOutput = utils.RemoveFields(defaultOutput, volatileFieldList())
}
output, err := buildOutputFromBody(responseBody, plan.ResponseExportValues, defaultOutput)
if err != nil {
diagnostics.AddError("Failed to build output", err.Error())
return
}
plan.Output = output
if bodyMap, ok := responseBody.(map[string]interface{}); ok {
if !plan.Identity.IsNull() {
planIdentity := identity.FromList(plan.Identity)
if v := identity.FlattenIdentity(bodyMap["identity"]); v != nil {
planIdentity.TenantID = v.TenantID
planIdentity.PrincipalID = v.PrincipalID
} else {
planIdentity.TenantID = types.StringNull()
planIdentity.PrincipalID = types.StringNull()
}
plan.Identity = identity.ToList(planIdentity)
}
}
diagnostics.Append(responseState.Set(ctx, plan)...)
}
}
diagnostics.AddError("Failed to create/update resource", fmt.Errorf("creating/updating %s: %+v", id, err).Error())
return
}
tflog.Debug(ctx, "azapi_resource.CreateUpdate get resource after creation")
requestOptions = clients.RequestOptions{
Headers: common.AsMapOfString(plan.ReadHeaders),
QueryParameters: clients.NewQueryParameters(common.AsMapOfLists(plan.ReadQueryParameters)),
RetryOptions: clients.CombineRetryOptions(
clients.NewRetryOptionsForReadAfterCreate(),
clients.NewRetryOptions(plan.Retry),
),
}
responseBody, err := client.Get(ctx, id.AzureResourceId, id.ApiVersion, requestOptions)
if err != nil {
if utils.ResponseErrorWasNotFound(err) {
tflog.Info(ctx, fmt.Sprintf("Error reading %q - removing from state", id.ID()))
responseState.RemoveResource(ctx)
return
}
diagnostics.AddError("Failed to retrieve resource", fmt.Errorf("reading %s: %+v", id, err).Error())
return
}
// generate the computed fields
plan.ID = types.StringValue(id.ID())
var defaultOutput interface{}
if !r.ProviderData.Features.DisableDefaultOutput {
defaultOutput = id.ResourceDef.GetReadOnly(responseBody)
defaultOutput = utils.RemoveFields(defaultOutput, volatileFieldList())
}
output, err := buildOutputFromBody(responseBody, plan.ResponseExportValues, defaultOutput)
if err != nil {
diagnostics.AddError("Failed to build output", err.Error())
return
}
plan.Output = output
if bodyMap, ok := responseBody.(map[string]interface{}); ok {
if !plan.Identity.IsNull() {
planIdentity := identity.FromList(plan.Identity)
if v := identity.FlattenIdentity(bodyMap["identity"]); v != nil {
planIdentity.TenantID = v.TenantID
planIdentity.PrincipalID = v.PrincipalID
} else {
planIdentity.TenantID = types.StringNull()
planIdentity.PrincipalID = types.StringNull()
}
plan.Identity = identity.ToList(planIdentity)
}
}
diagnostics.Append(responseState.Set(ctx, plan)...)
if plan.SensitiveBodyVersion.IsNull() {
writeOnlyBytes, err := dynamic.ToJSON(config.SensitiveBody)
if err != nil {
diagnostics.AddError("Invalid sensitive_body", err.Error())
return
}
diagnostics.Append(ephemeralBodyPrivateMgr.Set(ctx, privateData, writeOnlyBytes)...)
} else {
diagnostics.Append(ephemeralBodyPrivateMgr.Set(ctx, privateData, nil)...)
}
}
func (r *AzapiResource) Read(ctx context.Context, request resource.ReadRequest, response *resource.ReadResponse) {
var model AzapiResourceModel
if response.Diagnostics.Append(request.State.Get(ctx, &model)...); response.Diagnostics.HasError() {
return
}
readTimeout, diags := model.Timeouts.Read(ctx, 5*time.Minute)
response.Diagnostics.Append(diags...)
if response.Diagnostics.HasError() {
return
}
// Ensure the context deadline has been set before calling ConfigureClientWithCustomRetry().
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
id, err := parse.ResourceIDWithResourceType(model.ID.ValueString(), model.Type.ValueString())
if err != nil {
response.Diagnostics.AddError("Error parsing ID", err.Error())
return
}
ctx = tflog.SetField(ctx, "resource_id", id.ID())
client := r.ProviderData.ResourceClient
requestOptions := clients.RequestOptions{
Headers: common.AsMapOfString(model.ReadHeaders),
QueryParameters: clients.NewQueryParameters(common.AsMapOfLists(model.ReadQueryParameters)),
RetryOptions: clients.NewRetryOptions(model.Retry),
}
responseBody, err := client.Get(ctx, id.AzureResourceId, id.ApiVersion, requestOptions)
if err != nil {
if utils.ResponseErrorWasNotFound(err) {
tflog.Info(ctx, fmt.Sprintf("Error reading %q - removing from state", id.ID()))
response.State.RemoveResource(ctx)