-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathresource.go
More file actions
1141 lines (1026 loc) · 41.9 KB
/
resource.go
File metadata and controls
1141 lines (1026 loc) · 41.9 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 cdn
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/objectvalidator"
"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/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listdefault"
"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/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
"github.com/stackitcloud/stackit-sdk-go/services/cdn"
"github.com/stackitcloud/stackit-sdk-go/services/cdn/wait"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
cdnUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/cdn/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &distributionResource{}
_ resource.ResourceWithConfigure = &distributionResource{}
_ resource.ResourceWithImportState = &distributionResource{}
)
var schemaDescriptions = map[string]string{
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`distribution_id`\".",
"distribution_id": "CDN distribution ID",
"project_id": "STACKIT project ID associated with the distribution",
"status": "Status of the distribution",
"created_at": "Time when the distribution was created",
"updated_at": "Time when the distribution was last updated",
"errors": "List of distribution errors",
"domains": "List of configured domains for the distribution",
"config": "The distribution configuration",
"config_backend": "The configured backend for the distribution",
"config_regions": "The configured regions where content will be hosted",
"config_backend_type": "The configured backend type. ",
"config_optimizer": "Configuration for the Image Optimizer. This is a paid feature that automatically optimizes images to reduce their file size for faster delivery, leading to improved website performance and a better user experience.",
"config_backend_origin_url": "The configured backend type http for the distribution",
"config_backend_origin_request_headers": "The configured type http origin request headers for the backend",
"config_backend_geofencing": "The configured type http to configure countries where content is allowed. A map of URLs to a list of countries",
"config_blocked_countries": "The configured countries where distribution of content is blocked",
"domain_name": "The name of the domain",
"domain_status": "The status of the domain",
"domain_type": "The type of the domain. Each distribution has one domain of type \"managed\", and domains of type \"custom\" may be additionally created by the user",
"domain_errors": "List of domain errors",
"config_backend_bucket_url": "The URL of the bucket (e.g. https://s3.example.com). Required if type is 'bucket'.",
"config_backend_region": "The region where the bucket is hosted. Required if type is 'bucket'.",
"config_backend_credentials_access_key_id": "The access key for the bucket. Required if type is 'bucket'.",
"config_backend_credentials_secret_access_key": "The secret key for the bucket. Required if type is 'bucket'.",
"config_backend_credentials": "The credentials for the bucket. Required if type is 'bucket'.",
}
type Model struct {
ID types.String `tfsdk:"id"` // Required by Terraform
DistributionId types.String `tfsdk:"distribution_id"` // DistributionID associated with the cdn distribution
ProjectId types.String `tfsdk:"project_id"` // ProjectId associated with the cdn distribution
Status types.String `tfsdk:"status"` // The status of the cdn distribution
CreatedAt types.String `tfsdk:"created_at"` // When the distribution was created
UpdatedAt types.String `tfsdk:"updated_at"` // When the distribution was last updated
Errors types.List `tfsdk:"errors"` // Any errors that the distribution has
Domains types.List `tfsdk:"domains"` // The domains associated with the distribution
Config types.Object `tfsdk:"config"` // the configuration of the distribution
}
type distributionConfig struct {
Backend backend `tfsdk:"backend"` // The backend associated with the distribution
Regions *[]string `tfsdk:"regions"` // The regions in which data will be cached
BlockedCountries *[]string `tfsdk:"blocked_countries"` // The countries for which content will be blocked
Optimizer types.Object `tfsdk:"optimizer"` // The optimizer configuration
}
type optimizerConfig struct {
Enabled types.Bool `tfsdk:"enabled"`
}
type backend struct {
Type string `tfsdk:"type"` // The type of the backend. Currently, only "http" backend is supported
OriginURL *string `tfsdk:"origin_url"` // The origin URL of the backend
OriginRequestHeaders *map[string]string `tfsdk:"origin_request_headers"` // Request headers that should be added by the CDN distribution to incoming requests
Geofencing *map[string][]*string `tfsdk:"geofencing"` // The geofencing is an object mapping multiple alternative origins to country codes.
BucketURL *string `tfsdk:"bucket_url"`
Region *string `tfsdk:"region"`
Credentials *backendCredentials `tfsdk:"credentials"`
}
type backendCredentials struct {
AccessKey *string `tfsdk:"access_key_id"` //nolint:gosec // AccessKey should be exported from this struct
SecretKey *string `tfsdk:"secret_access_key"`
}
var configTypes = map[string]attr.Type{
"backend": types.ObjectType{AttrTypes: backendTypes},
"regions": types.ListType{ElemType: types.StringType},
"blocked_countries": types.ListType{ElemType: types.StringType},
"optimizer": types.ObjectType{
AttrTypes: optimizerTypes,
},
}
var optimizerTypes = map[string]attr.Type{
"enabled": types.BoolType,
}
var geofencingTypes = types.MapType{ElemType: types.ListType{
ElemType: types.StringType,
}}
var backendTypes = map[string]attr.Type{
"type": types.StringType,
"origin_url": types.StringType,
"origin_request_headers": types.MapType{ElemType: types.StringType},
"geofencing": geofencingTypes,
"bucket_url": types.StringType,
"region": types.StringType,
"credentials": types.ObjectType{AttrTypes: backendCredentialsTypes},
}
var backendCredentialsTypes = map[string]attr.Type{
"access_key_id": types.StringType,
"secret_access_key": types.StringType,
}
var domainTypes = map[string]attr.Type{
"name": types.StringType,
"status": types.StringType,
"type": types.StringType,
"errors": types.ListType{ElemType: types.StringType},
}
type distributionResource struct {
client *cdn.APIClient
providerData core.ProviderData
}
func NewDistributionResource() resource.Resource {
return &distributionResource{}
}
func (r *distributionResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
var ok bool
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
features.CheckBetaResourcesEnabled(ctx, &r.providerData, &resp.Diagnostics, "stackit_cdn_distribution", "resource")
if resp.Diagnostics.HasError() {
return
}
apiClient := cdnUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
tflog.Info(ctx, "CDN client configured")
}
func (r *distributionResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_cdn_distribution"
}
func (r *distributionResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
backendOptions := []string{"http", "bucket"}
resp.Schema = schema.Schema{
MarkdownDescription: features.AddBetaDescription("CDN distribution data source schema.", core.Resource),
Description: "CDN distribution data source schema.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: schemaDescriptions["id"],
Computed: true,
},
"distribution_id": schema.StringAttribute{
Description: schemaDescriptions["distribution_id"],
Computed: true,
Validators: []validator.String{validate.UUID()},
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"project_id": schema.StringAttribute{
Description: schemaDescriptions["project_id"],
Required: true,
Optional: false,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"status": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["status"],
},
"created_at": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["created_at"],
},
"updated_at": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["updated_at"],
},
"errors": schema.ListAttribute{
ElementType: types.StringType,
Computed: true,
Description: schemaDescriptions["errors"],
},
"domains": schema.ListNestedAttribute{
Computed: true,
Description: schemaDescriptions["domains"],
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["domain_name"],
},
"status": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["domain_status"],
},
"type": schema.StringAttribute{
Computed: true,
Description: schemaDescriptions["domain_type"],
},
"errors": schema.ListAttribute{
Computed: true,
Description: schemaDescriptions["domain_errors"],
ElementType: types.StringType,
},
},
},
},
"config": schema.SingleNestedAttribute{
Required: true,
Description: schemaDescriptions["config"],
Attributes: map[string]schema.Attribute{
"optimizer": schema.SingleNestedAttribute{
Description: schemaDescriptions["config_optimizer"],
Optional: true,
Computed: true,
Attributes: map[string]schema.Attribute{
"enabled": schema.BoolAttribute{
Optional: true,
Computed: true,
},
},
Validators: []validator.Object{
objectvalidator.AlsoRequires(path.MatchRelative().AtName("enabled")),
},
},
"backend": schema.SingleNestedAttribute{
Required: true,
Description: schemaDescriptions["config_backend"],
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
Required: true,
Description: schemaDescriptions["config_backend_type"] + utils.FormatPossibleValues(backendOptions...),
Validators: []validator.String{stringvalidator.OneOf(backendOptions...)},
},
"origin_url": schema.StringAttribute{
Optional: true,
Description: schemaDescriptions["config_backend_origin_url"],
Validators: []validator.String{
stringvalidator.ConflictsWith(
// If the origin_url field is populated, no bucket fields can be used
path.MatchRelative().AtParent().AtName("bucket_url"),
path.MatchRelative().AtParent().AtName("region"),
path.MatchRelative().AtParent().AtName("credentials"),
),
},
},
"origin_request_headers": schema.MapAttribute{
Optional: true,
Description: schemaDescriptions["config_backend_origin_request_headers"],
ElementType: types.StringType,
Validators: []validator.Map{
mapvalidator.AlsoRequires(path.MatchRelative().AtParent().AtName("origin_url")),
},
},
"geofencing": schema.MapAttribute{
Description: schemaDescriptions["config_backend_geofencing"],
Optional: true,
ElementType: types.ListType{
ElemType: types.StringType,
},
Validators: []validator.Map{
mapvalidator.SizeAtLeast(1),
mapvalidator.AlsoRequires(path.MatchRelative().AtParent().AtName("origin_url")),
},
},
"bucket_url": schema.StringAttribute{
Optional: true,
Description: schemaDescriptions["config_backend_bucket_url"],
Validators: []validator.String{
stringvalidator.AlsoRequires(path.MatchRelative().AtParent().AtName("region"), path.MatchRelative().AtParent().AtName("credentials")),
stringvalidator.ConflictsWith(
// If the origin_url is populated, bucket_url can not be used
path.MatchRelative().AtParent().AtName("origin_url"),
),
},
},
"region": schema.StringAttribute{
Optional: true,
Description: schemaDescriptions["config_backend_region"],
Validators: []validator.String{stringvalidator.AlsoRequires((path.MatchRelative().AtParent().AtName("bucket_url")))},
},
"credentials": schema.SingleNestedAttribute{
Optional: true,
Description: schemaDescriptions["config_backend_credentials"],
Attributes: map[string]schema.Attribute{
"access_key_id": schema.StringAttribute{
Required: true,
Sensitive: true,
Description: schemaDescriptions["config_backend_credentials_access_key_id"],
},
"secret_access_key": schema.StringAttribute{
Required: true,
Sensitive: true,
Description: schemaDescriptions["config_backend_credentials_access_key_id"],
},
},
Validators: []validator.Object{objectvalidator.AlsoRequires((path.MatchRelative().AtParent().AtName("bucket_url")))},
},
},
},
"regions": schema.ListAttribute{
Required: true,
Description: schemaDescriptions["config_regions"],
ElementType: types.StringType,
},
"blocked_countries": schema.ListAttribute{
Optional: true,
Computed: true, // Required when using Default
Description: schemaDescriptions["config_blocked_countries"],
ElementType: types.StringType,
// The API returns an empty list for blocked_countries even if the field is omitted
// (null) in the request. This causes an "inconsistent result" error in Terraform
// because the config is null but the state is [].
//
// By setting a Default value of an empty list, we tell Terraform to treat a missing
// blocked_countries block in the HCL as if the user explicitly defined
// blocked_countries = []. This ensures the config (empty list) matches the
// API response (empty list).
Default: listdefault.StaticValue(types.ListValueMust(types.StringType, []attr.Value{})),
},
},
},
},
}
}
func (r *distributionResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
var model Model
resp.Diagnostics.Append(req.Config.Get(ctx, &model)...)
if resp.Diagnostics.HasError() {
return
}
if !utils.IsUndefined(model.Config) {
var config distributionConfig
if !model.Config.IsNull() {
diags := model.Config.As(ctx, &config, basetypes.ObjectAsOptions{})
if diags.HasError() {
return
}
if geofencing := config.Backend.Geofencing; geofencing != nil {
for url, region := range *geofencing {
if region == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Invalid geofencing config", fmt.Sprintf("The list of countries for URL %q must not be null.", url))
continue
}
if len(region) == 0 {
core.LogAndAddError(ctx, &resp.Diagnostics, "Invalid geofencing config", fmt.Sprintf("The list of countries for URL %q must not be empty.", url))
continue
}
for i, countryPtr := range region {
if countryPtr == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Invalid geofencing config", fmt.Sprintf("Found a null value in the country list for URL %q at index %d.", url, i))
break
}
}
}
}
}
}
}
func (r *distributionResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
payload, err := toCreatePayload(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating CDN distribution", fmt.Sprintf("Creating API payload: %v", err))
return
}
createResp, err := r.client.CreateDistribution(ctx, projectId).CreateDistributionPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating CDN distribution", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
if createResp.Distribution.Id == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating CDN distribution", "Got empty cdn distribution id")
return
}
// Write id attributes to state before polling via the wait handler - just in case anything goes wrong during the wait handler
ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": projectId,
"distribution_id": *createResp.Distribution.Id,
})
if resp.Diagnostics.HasError() {
return
}
waitResp, err := wait.CreateDistributionPoolWaitHandler(ctx, r.client, projectId, *createResp.Distribution.Id).SetTimeout(5 * time.Minute).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating CDN distribution", fmt.Sprintf("Waiting for create: %v", err))
return
}
err = mapFields(ctx, waitResp.Distribution, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating CDN distribution", fmt.Sprintf("Processing API payload: %v", err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "CDN distribution created")
}
func (r *distributionResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
distributionId := model.DistributionId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "distribution_id", distributionId)
cdnResp, err := r.client.GetDistribution(ctx, projectId, distributionId).Execute()
if err != nil {
var oapiErr *oapierror.GenericOpenAPIError
// n.b. err is caught here if of type *oapierror.GenericOpenAPIError, which the stackit SDK client returns
if errors.As(err, &oapiErr) {
if oapiErr.StatusCode == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}
}
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading CDN distribution", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
err = mapFields(ctx, cdnResp.Distribution, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading CDN ditribution", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "CDN distribution read")
}
func (r *distributionResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
distributionId := model.DistributionId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "distribution_id", distributionId)
configModel := distributionConfig{}
diags = model.Config.As(ctx, &configModel, basetypes.ObjectAsOptions{
UnhandledNullAsEmpty: false,
UnhandledUnknownAsEmpty: false,
})
if diags.HasError() {
core.LogAndAddError(ctx, &resp.Diagnostics, "Update CDN distribution", "Error mapping config")
return
}
regions := []cdn.Region{}
for _, r := range *configModel.Regions {
regionEnum, err := cdn.NewRegionFromValue(r)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Update CDN distribution", fmt.Sprintf("Map regions: %v", err))
return
}
regions = append(regions, *regionEnum)
}
// blockedCountries
// Use a pointer to a slice to distinguish between an empty list (unblock all) and nil (no change).
var blockedCountries *[]string
if configModel.BlockedCountries != nil {
// Use a temporary slice
tempBlockedCountries := []string{}
for _, blockedCountry := range *configModel.BlockedCountries {
validatedBlockedCountry, err := validateCountryCode(blockedCountry)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Update CDN distribution", fmt.Sprintf("Blocked countries: %v", err))
return
}
tempBlockedCountries = append(tempBlockedCountries, validatedBlockedCountry)
}
// Point to the populated slice
blockedCountries = &tempBlockedCountries
}
configPatchBackend := &cdn.ConfigPatchBackend{}
if configModel.Backend.Type == "http" {
geofencingPatch := map[string][]string{}
if configModel.Backend.Geofencing != nil {
gf := make(map[string][]string)
for url, countries := range *configModel.Backend.Geofencing {
countryStrings := make([]string, len(countries))
for i, countryPtr := range countries {
if countryPtr == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Update CDN distribution", fmt.Sprintf("Geofencing url %q has a null value", url))
return
}
countryStrings[i] = *countryPtr
}
gf[url] = countryStrings
}
geofencingPatch = gf
}
configPatchBackend.HttpBackendPatch = &cdn.HttpBackendPatch{
OriginRequestHeaders: configModel.Backend.OriginRequestHeaders,
OriginUrl: configModel.Backend.OriginURL,
Type: cdn.PtrString("http"),
Geofencing: &geofencingPatch,
}
} else if configModel.Backend.Type == "bucket" {
configPatchBackend.BucketBackendPatch = &cdn.BucketBackendPatch{
Type: cdn.PtrString("bucket"),
BucketUrl: configModel.Backend.BucketURL,
Region: configModel.Backend.Region,
}
if configModel.Backend.Credentials != nil {
configPatchBackend.BucketBackendPatch.Credentials = &cdn.BucketCredentials{
AccessKeyId: configModel.Backend.Credentials.AccessKey,
SecretAccessKey: configModel.Backend.Credentials.SecretKey,
}
}
}
configPatch := &cdn.ConfigPatch{
Backend: configPatchBackend,
Regions: ®ions,
BlockedCountries: blockedCountries,
}
if !utils.IsUndefined(configModel.Optimizer) {
var optimizerModel optimizerConfig
diags = configModel.Optimizer.As(ctx, &optimizerModel, basetypes.ObjectAsOptions{})
if diags.HasError() {
core.LogAndAddError(ctx, &resp.Diagnostics, "Update CDN distribution", "Error mapping optimizer config")
return
}
optimizer := cdn.NewOptimizerPatch()
if !utils.IsUndefined(optimizerModel.Enabled) {
optimizer.SetEnabled(optimizerModel.Enabled.ValueBool())
}
configPatch.Optimizer = optimizer
}
_, err := r.client.PatchDistribution(ctx, projectId, distributionId).PatchDistributionPayload(cdn.PatchDistributionPayload{
Config: configPatch,
IntentId: cdn.PtrString(uuid.NewString()),
}).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Update CDN distribution", fmt.Sprintf("Patch distribution: %v", err))
return
}
ctx = core.LogResponse(ctx)
waitResp, err := wait.UpdateDistributionWaitHandler(ctx, r.client, projectId, distributionId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Update CDN distribution", fmt.Sprintf("Waiting for update: %v", err))
return
}
err = mapFields(ctx, waitResp.Distribution, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Update CDN distribution", fmt.Sprintf("Processing API payload: %v", err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "CDN distribution updated")
}
func (r *distributionResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.LogResponse(ctx)
projectId := model.ProjectId.ValueString()
distributionId := model.DistributionId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "distribution_id", distributionId)
_, err := r.client.DeleteDistribution(ctx, projectId, distributionId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Delete CDN distribution", fmt.Sprintf("Delete distribution: %v", err))
}
ctx = core.LogResponse(ctx)
_, err = wait.DeleteDistributionWaitHandler(ctx, r.client, projectId, distributionId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Delete CDN distribution", fmt.Sprintf("Waiting for deletion: %v", err))
return
}
tflog.Info(ctx, "CDN distribution deleted")
}
func (r *distributionResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error importing CDN distribution", fmt.Sprintf("Expected import identifier on the format: [project_id]%q[distribution_id], got %q", core.Separator, req.ID))
}
ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]interface{}{
"project_id": idParts[0],
"distribution_id": idParts[1],
})
tflog.Info(ctx, "CDN distribution state imported")
}
func mapFields(ctx context.Context, distribution *cdn.Distribution, model *Model) error {
if distribution == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
if distribution.ProjectId == nil {
return fmt.Errorf("Project ID not present")
}
if distribution.Id == nil {
return fmt.Errorf("CDN distribution ID not present")
}
if distribution.CreatedAt == nil {
return fmt.Errorf("CreatedAt missing in response")
}
if distribution.UpdatedAt == nil {
return fmt.Errorf("UpdatedAt missing in response")
}
if distribution.Status == nil {
return fmt.Errorf("Status missing in response")
}
model.ID = utils.BuildInternalTerraformId(*distribution.ProjectId, *distribution.Id)
model.DistributionId = types.StringValue(*distribution.Id)
model.ProjectId = types.StringValue(*distribution.ProjectId)
model.Status = types.StringValue(string(distribution.GetStatus()))
model.CreatedAt = types.StringValue(distribution.CreatedAt.String())
model.UpdatedAt = types.StringValue(distribution.UpdatedAt.String())
// distributionErrors
distributionErrors := []attr.Value{}
if distribution.Errors != nil {
for _, e := range *distribution.Errors {
distributionErrors = append(distributionErrors, types.StringValue(*e.En))
}
}
modelErrors, diags := types.ListValue(types.StringType, distributionErrors)
if diags.HasError() {
return core.DiagsToError(diags)
}
model.Errors = modelErrors
// regions
regions := []attr.Value{}
for _, r := range *distribution.Config.Regions {
regions = append(regions, types.StringValue(string(r)))
}
modelRegions, diags := types.ListValue(types.StringType, regions)
if diags.HasError() {
return core.DiagsToError(diags)
}
// Check if we have existing configuration to preserve secrets
var oldConfig distributionConfig
if !utils.IsUndefined(model.Config) {
diags := model.Config.As(ctx, &oldConfig, basetypes.ObjectAsOptions{
UnhandledNullAsEmpty: false,
UnhandledUnknownAsEmpty: false,
})
if diags.HasError() {
return core.DiagsToError(diags)
}
}
// blockedCountries
var blockedCountries []attr.Value
if distribution.Config != nil && distribution.Config.BlockedCountries != nil {
for _, c := range *distribution.Config.BlockedCountries {
blockedCountries = append(blockedCountries, types.StringValue(string(c)))
}
}
modelBlockedCountries, diags := types.ListValue(types.StringType, blockedCountries)
if diags.HasError() {
return core.DiagsToError(diags)
}
// originRequestHeaders
originRequestHeaders := types.MapNull(types.StringType)
if distribution.Config.Backend.HttpBackend != nil {
if origHeaders := distribution.Config.Backend.HttpBackend.OriginRequestHeaders; origHeaders != nil && len(*origHeaders) > 0 {
headers := map[string]attr.Value{}
for k, v := range *origHeaders {
headers[k] = types.StringValue(v)
}
mappedHeaders, diags := types.MapValue(types.StringType, headers)
originRequestHeaders = mappedHeaders
if diags.HasError() {
return core.DiagsToError(diags)
}
}
}
// geofencing
oldGeofencingMap := make(map[string][]*string)
if oldConfig.Backend.Geofencing != nil {
oldGeofencingMap = *oldConfig.Backend.Geofencing
}
reconciledGeofencingData := make(map[string][]string)
if distribution.Config.Backend.HttpBackend != nil {
if geofencingAPI := distribution.Config.Backend.HttpBackend.Geofencing; geofencingAPI != nil && len(*geofencingAPI) > 0 {
newGeofencingMap := *geofencingAPI
for url, newCountries := range newGeofencingMap {
oldCountriesPtrs := oldGeofencingMap[url]
oldCountries := utils.ConvertPointerSliceToStringSlice(oldCountriesPtrs)
reconciledCountries := utils.ReconcileStringSlices(oldCountries, newCountries)
reconciledGeofencingData[url] = reconciledCountries
}
}
}
geofencingVal := types.MapNull(geofencingTypes.ElemType)
if len(reconciledGeofencingData) > 0 {
geofencingMapElems := make(map[string]attr.Value)
for url, countries := range reconciledGeofencingData {
listVal, diags := types.ListValueFrom(ctx, types.StringType, countries)
if diags.HasError() {
return core.DiagsToError(diags)
}
geofencingMapElems[url] = listVal
}
var mappedGeofencing basetypes.MapValue
mappedGeofencing, diags = types.MapValue(geofencingTypes.ElemType, geofencingMapElems)
if diags.HasError() {
return core.DiagsToError(diags)
}
geofencingVal = mappedGeofencing
}
// Map Backend Fields (HTTP or Bucket)
var backendValues map[string]attr.Value
if distribution.Config.Backend.HttpBackend != nil {
backendValues = map[string]attr.Value{
"type": types.StringValue("http"),
"origin_url": types.StringValue(*distribution.Config.Backend.HttpBackend.OriginUrl),
"origin_request_headers": originRequestHeaders,
"geofencing": geofencingVal,
// bucket fields must be null when using HTTP
"bucket_url": types.StringNull(),
"region": types.StringNull(),
"credentials": types.ObjectNull(backendCredentialsTypes),
}
} else if distribution.Config.Backend.BucketBackend != nil {
// Preserve secrets from previous state because API does not return them
accessKeyVal := types.StringNull()
secretKeyVal := types.StringNull()
if oldConfig.Backend.Credentials != nil && oldConfig.Backend.Credentials.AccessKey != nil {
accessKeyVal = types.StringValue(*oldConfig.Backend.Credentials.AccessKey)
}
if oldConfig.Backend.Credentials != nil && oldConfig.Backend.Credentials.SecretKey != nil {
secretKeyVal = types.StringValue(*oldConfig.Backend.Credentials.SecretKey)
}
credentialsObj, diags := types.ObjectValue(backendCredentialsTypes, map[string]attr.Value{
"access_key_id": accessKeyVal,
"secret_access_key": secretKeyVal,
})
if diags.HasError() {
return core.DiagsToError(diags)
}
backendValues = map[string]attr.Value{
"type": types.StringValue("bucket"),
"bucket_url": types.StringValue(*distribution.Config.Backend.BucketBackend.BucketUrl),
"region": types.StringValue(*distribution.Config.Backend.BucketBackend.Region),
"credentials": credentialsObj,
// HTTP field must be null when using Bucket
"origin_url": types.StringNull(),
"origin_request_headers": types.MapNull(types.StringType),
"geofencing": types.MapNull(geofencingTypes.ElemType),
}
}
// note that httpbackend is hardcoded here as long as it is the only available backend
backend, diags := types.ObjectValue(backendTypes, backendValues)
if diags.HasError() {
return core.DiagsToError(diags)
}
optimizerVal := types.ObjectNull(optimizerTypes)
if o := distribution.Config.Optimizer; o != nil {
optimizerEnabled, ok := o.GetEnabledOk()
if ok {
var diags diag.Diagnostics
optimizerVal, diags = types.ObjectValue(optimizerTypes, map[string]attr.Value{
"enabled": types.BoolValue(optimizerEnabled),
})
if diags.HasError() {
return core.DiagsToError(diags)
}
}
}
cfg, diags := types.ObjectValue(configTypes, map[string]attr.Value{
"backend": backend,
"regions": modelRegions,
"blocked_countries": modelBlockedCountries,
"optimizer": optimizerVal,
})
if diags.HasError() {
return core.DiagsToError(diags)
}
model.Config = cfg
domains := []attr.Value{}
if distribution.Domains != nil {
for _, d := range *distribution.Domains {
domainErrors := []attr.Value{}
if d.Errors != nil {
for _, e := range *d.Errors {
if e.En == nil {
return fmt.Errorf("error description missing")
}
domainErrors = append(domainErrors, types.StringValue(*e.En))
}
}
modelDomainErrors, diags := types.ListValue(types.StringType, domainErrors)
if diags.HasError() {
return core.DiagsToError(diags)
}
if d.Name == nil || d.Status == nil || d.Type == nil {
return fmt.Errorf("domain entry incomplete")
}
modelDomain, diags := types.ObjectValue(domainTypes, map[string]attr.Value{
"name": types.StringValue(*d.Name),
"status": types.StringValue(string(*d.Status)),
"type": types.StringValue(string(*d.Type)),
"errors": modelDomainErrors,
})
if diags.HasError() {
return core.DiagsToError(diags)
}
domains = append(domains, modelDomain)
}
}
modelDomains, diags := types.ListValue(types.ObjectType{AttrTypes: domainTypes}, domains)
if diags.HasError() {
return core.DiagsToError(diags)
}
model.Domains = modelDomains
return nil
}
func toCreatePayload(ctx context.Context, model *Model) (*cdn.CreateDistributionPayload, error) {
if model == nil {
return nil, fmt.Errorf("missing model")
}
cfg, err := convertConfig(ctx, model)
if err != nil {
return nil, err
}
var optimizer *cdn.Optimizer
if cfg.Optimizer != nil {
optimizer = cdn.NewOptimizer(cfg.Optimizer.GetEnabled())
}
var backend *cdn.CreateDistributionPayloadBackend
if cfg.Backend.HttpBackend != nil {
backend = &cdn.CreateDistributionPayloadBackend{
HttpBackendCreate: &cdn.HttpBackendCreate{
OriginUrl: cfg.Backend.HttpBackend.OriginUrl,
OriginRequestHeaders: cfg.Backend.HttpBackend.OriginRequestHeaders,
Geofencing: cfg.Backend.HttpBackend.Geofencing,
Type: cdn.PtrString("http"),
},
}
} else if cfg.Backend.BucketBackend != nil {
// We need to parse the model again to access the credentials,
// as convertConfig returns the SDK Config struct which hides them.
var rawConfig distributionConfig
diags := model.Config.As(ctx, &rawConfig, basetypes.ObjectAsOptions{
UnhandledNullAsEmpty: false,
UnhandledUnknownAsEmpty: false,
})
if diags.HasError() {
return nil, core.DiagsToError(diags)
}
var accessKey, secretKey *string
if rawConfig.Backend.Credentials != nil {
accessKey = rawConfig.Backend.Credentials.AccessKey
secretKey = rawConfig.Backend.Credentials.SecretKey
}
backend = &cdn.CreateDistributionPayloadBackend{
BucketBackendCreate: &cdn.BucketBackendCreate{
Type: cdn.PtrString("bucket"),