-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathresource.go
More file actions
810 lines (726 loc) · 30.2 KB
/
Copy pathresource.go
File metadata and controls
810 lines (726 loc) · 30.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
package volume
import (
"context"
"fmt"
"net/http"
"regexp"
"strings"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
sdkUtils "github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
"github.com/hashicorp/terraform-plugin-framework-validators/resourcevalidator"
"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/objectplanmodifier"
"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/iaas"
"github.com/stackitcloud/stackit-sdk-go/services/iaas/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/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &volumeResource{}
_ resource.ResourceWithConfigure = &volumeResource{}
_ resource.ResourceWithImportState = &volumeResource{}
_ resource.ResourceWithModifyPlan = &volumeResource{}
SupportedSourceTypes = []string{"volume", "image", "snapshot", "backup"}
)
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
VolumeId types.String `tfsdk:"volume_id"`
Name types.String `tfsdk:"name"`
AvailabilityZone types.String `tfsdk:"availability_zone"`
Labels types.Map `tfsdk:"labels"`
Description types.String `tfsdk:"description"`
PerformanceClass types.String `tfsdk:"performance_class"`
Size types.Int64 `tfsdk:"size"`
ServerId types.String `tfsdk:"server_id"`
Source types.Object `tfsdk:"source"`
EncryptionParameters *encryptionParametersModel `tfsdk:"encryption_parameters"`
Encrypted types.Bool `tfsdk:"encrypted"`
}
type encryptionParametersModel struct {
KekKeyId types.String `tfsdk:"kek_key_id"`
KekKeyVersion types.Int64 `tfsdk:"kek_key_version"`
KekKeyringId types.String `tfsdk:"kek_keyring_id"`
KeyPayloadBase64 types.String `tfsdk:"key_payload_base64"`
KeyPayloadBase64WriteOnly types.String `tfsdk:"key_payload_base64_wo"`
KeyPayloadBase64WriteOnlyVersion types.Int64 `tfsdk:"key_payload_base64_wo_version"`
ServiceAccount types.String `tfsdk:"service_account"`
}
// Struct corresponding to Model.Source
type sourceModel struct {
Type types.String `tfsdk:"type"`
Id types.String `tfsdk:"id"`
}
// Types corresponding to sourceModel
var sourceTypes = map[string]attr.Type{
"type": basetypes.StringType{},
"id": basetypes.StringType{},
}
// NewVolumeResource is a helper function to simplify the provider implementation.
func NewVolumeResource() resource.Resource {
return &volumeResource{}
}
// volumeResource is the resource implementation.
type volumeResource struct {
client *iaas.APIClient
providerData core.ProviderData
}
// Metadata returns the resource type name.
func (r *volumeResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_volume"
}
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan.
func (r *volumeResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
var configModel Model
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
}
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
if resp.Diagnostics.HasError() {
return
}
var planModel Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
}
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
if resp.Diagnostics.HasError() {
return
}
}
// ConfigValidators validates the resource configuration
func (r *volumeResource) ConfigValidators(_ context.Context) []resource.ConfigValidator {
return []resource.ConfigValidator{
resourcevalidator.AtLeastOneOf(
path.MatchRoot("source"),
path.MatchRoot("size"),
),
}
}
// Configure adds the provider configured client to the resource.
func (r *volumeResource) 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
}
apiClient := iaasUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
tflog.Info(ctx, "iaas client configured")
}
// Schema defines the schema for the resource.
func (r *volumeResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
description := "Volume resource schema. Must have a `region` specified in the provider configuration."
resp.Schema = schema.Schema{
MarkdownDescription: fmt.Sprintf("%s \n\n-> **Note:** Write-Only argument `key_payload_base64_wo` is available to use in place of `key_payload_base64`. Write-Only arguments are supported in HashiCorp Terraform 1.11.0 and later. [Learn more](https://developer.hashicorp.com/terraform/language/resources/ephemeral#write-only-arguments).", description),
Description: description,
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`volume_id`\".",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"project_id": schema.StringAttribute{
Description: "STACKIT project ID to which the volume is associated.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"region": schema.StringAttribute{
Description: "The resource region. If not defined, the provider region is used.",
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"volume_id": schema.StringAttribute{
Description: "The volume ID.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"server_id": schema.StringAttribute{
Description: "The server ID of the server to which the volume is attached to.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"name": schema.StringAttribute{
Description: "The name of the volume.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.LengthAtMost(63),
stringvalidator.RegexMatches(
regexp.MustCompile(`^[A-Za-z0-9]+((-|_|\s|\.)[A-Za-z0-9]+)*$`),
"must match expression"),
},
},
"description": schema.StringAttribute{
Description: "The description of the volume.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.LengthAtMost(127),
},
},
"availability_zone": schema.StringAttribute{
Description: "The availability zone of the volume.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Required: true,
},
"labels": schema.MapAttribute{
Description: "Labels are key-value string pairs which can be attached to a resource container",
ElementType: types.StringType,
Optional: true,
},
"performance_class": schema.StringAttribute{
MarkdownDescription: "The performance class of the volume. Possible values are documented in [Service plans BlockStorage](https://docs.stackit.cloud/products/storage/block-storage/basics/service-plans/#currently-available-service-plans-performance-classes)",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.LengthAtMost(63),
stringvalidator.RegexMatches(
regexp.MustCompile(`^[A-Za-z0-9]+((-|_|\s|\.)[A-Za-z0-9]+)*$`),
"must match expression"),
},
},
"size": schema.Int64Attribute{
Description: "The size of the volume in GB. It can only be updated to a larger value than the current size. Either `size` or `source` must be provided",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Int64{
volumeResizeModifier{},
},
},
"source": schema.SingleNestedAttribute{
Description: "The source of the volume. It can be either a volume, an image, a snapshot or a backup. Either `size` or `source` must be provided",
Optional: true,
PlanModifiers: []planmodifier.Object{
objectplanmodifier.RequiresReplace(),
},
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
Description: "The type of the source. " + utils.FormatPossibleValues(SupportedSourceTypes...),
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"id": schema.StringAttribute{
Description: "The ID of the source, e.g. image ID",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
},
"encryption_parameters": schema.SingleNestedAttribute{
Description: "Parameter to connect to a key-encryption-key within the STACKIT-KMS to create encrypted volumes. These parameters never leave the backend again. So these parameters are not present on imports or in the datasource. They live only in your Terraform state after creation of the resource.",
Optional: true,
PlanModifiers: []planmodifier.Object{
objectplanmodifier.RequiresReplace(),
},
Attributes: map[string]schema.Attribute{
"kek_key_id": schema.StringAttribute{
Description: "UUID of the key within the STACKIT-KMS to use for the encryption.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"kek_key_version": schema.Int64Attribute{
Description: "Version of the key within the STACKIT-KMS to use for the encryption.",
Required: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.RequiresReplace(),
},
},
"kek_keyring_id": schema.StringAttribute{
Description: "UUID of the keyring where the key is located within the STACKTI-KMS.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"key_payload_base64": schema.StringAttribute{
Description: "Optional predefined secret, which will be encrypted against the key-encryption-key within the STACKIT-KMS. If not defined, a random secret will be generated by the API and encrypted against the STACKIT-KMS. If a key-payload is provided here, it must be base64 encoded.",
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
stringvalidator.ConflictsWith(
path.MatchRelative().AtParent().AtName("key_payload_base64_wo"),
path.MatchRelative().AtParent().AtName("key_payload_base64_wo_version"),
),
stringvalidator.PreferWriteOnlyAttribute(path.MatchRoot("encryption_parameters").AtName("key_payload_base64_wo")),
},
Sensitive: true,
},
"key_payload_base64_wo": schema.StringAttribute{
Description: "Optional predefined secret, which will be encrypted against the key-encryption-key within the STACKIT-KMS. If not defined, a random secret will be generated by the API and encrypted against the STACKIT-KMS. If a key-payload is provided here, it must be base64 encoded.",
WriteOnly: true,
Optional: true,
Sensitive: true,
Validators: []validator.String{
stringvalidator.ConflictsWith(path.MatchRelative().AtParent().AtName("key_payload_base64")),
stringvalidator.AlsoRequires(path.MatchRelative().AtParent().AtName("key_payload_base64_wo_version")),
},
},
"key_payload_base64_wo_version": schema.Int64Attribute{
Description: "Used together with `key_payload_base64_wo` to trigger an re-create. Increment this value when an update to `key_payload_base64_wo` is required.",
Optional: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.RequiresReplace(),
},
Validators: []validator.Int64{
int64validator.AlsoRequires(path.MatchRelative().AtParent().AtName("key_payload_base64_wo")),
int64validator.ConflictsWith(path.MatchRelative().AtParent().AtName("key_payload_base64")),
},
},
"service_account": schema.StringAttribute{
Description: "Service-Account linked to the Key within the STACKIT-KMS.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
},
"encrypted": schema.BoolAttribute{
Description: "Indicates if the volume is encrypted.",
Computed: true,
},
},
}
}
var _ planmodifier.Int64 = volumeResizeModifier{}
type volumeResizeModifier struct {
}
// Description implements planmodifier.String.
func (v volumeResizeModifier) Description(context.Context) string {
return "validates volume resize"
}
// MarkdownDescription implements planmodifier.String.
func (v volumeResizeModifier) MarkdownDescription(ctx context.Context) string {
return v.Description(ctx)
}
// PlanModifyInt64 implements planmodifier.Int64.
func (v volumeResizeModifier) PlanModifyInt64(ctx context.Context, req planmodifier.Int64Request, resp *planmodifier.Int64Response) { // nolint:gocritic // function signature required by Terraform
var planSize types.Int64
var currentSize types.Int64
resp.Diagnostics.Append(req.Plan.GetAttribute(ctx, path.Root("size"), &planSize)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("size"), ¤tSize)...)
if resp.Diagnostics.HasError() {
return
}
if planSize.ValueInt64() < currentSize.ValueInt64() {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error changing volume size", "A volume cannot be made smaller in order to prevent data loss.")
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *volumeResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
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()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
var source = &sourceModel{}
if !(model.Source.IsNull() || model.Source.IsUnknown()) {
diags = model.Source.As(ctx, source, basetypes.ObjectAsOptions{})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Generate API request body from model
payload, err := toCreatePayload(ctx, &model, source)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating volume", fmt.Sprintf("Creating API payload: %v", err))
return
}
// Create new volume
volume, err := r.client.CreateVolume(ctx, projectId, region).CreateVolumePayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating volume", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
if volume.Id == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating volume", "Got empty volume id")
return
}
volumeId := *volume.Id
// 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,
"region": region,
"volume_id": volumeId,
})
if resp.Diagnostics.HasError() {
return
}
volume, err = wait.CreateVolumeWaitHandler(ctx, r.client, projectId, region, volumeId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating volume", fmt.Sprintf("volume creation waiting: %v", err))
return
}
// Map response body to schema
err = mapFields(ctx, volume, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating volume", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Volume created")
}
// Read refreshes the Terraform state with the latest data.
func (r *volumeResource) 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
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
volumeId := model.VolumeId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "volume_id", volumeId)
volumeResp, err := r.client.GetVolume(ctx, projectId, region, volumeId).Execute()
if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading volume", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
// Map response body to schema
err = mapFields(ctx, volumeResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading volume", 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, "volume read")
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *volumeResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
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()
region := r.providerData.GetRegionWithOverride(model.Region)
volumeId := model.VolumeId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "volume_id", volumeId)
// Retrieve values from state
var stateModel Model
diags = req.State.Get(ctx, &stateModel)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Generate API request body from model
payload, err := toUpdatePayload(ctx, &model, stateModel.Labels)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating volume", fmt.Sprintf("Creating API payload: %v", err))
return
}
// Update existing volume
updatedVolume, err := r.client.UpdateVolume(ctx, projectId, region, volumeId).UpdateVolumePayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating volume", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
// Resize existing volume
modelSize := conversion.Int64ValueToPointer(model.Size)
if modelSize != nil && updatedVolume.Size != nil {
// A volume can only be resized to larger values, otherwise an error occurs
if *modelSize < *updatedVolume.Size {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating volume", fmt.Sprintf("The new volume size must be larger than the current size (%d GB)", *updatedVolume.Size))
} else if *modelSize > *updatedVolume.Size {
payload := iaas.ResizeVolumePayload{
Size: modelSize,
}
err := r.client.ResizeVolume(ctx, projectId, region, volumeId).ResizeVolumePayload(payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating volume", fmt.Sprintf("Resizing the volume, calling API: %v", err))
}
// Update volume model because the API doesn't return a volume object as response
updatedVolume.Size = modelSize
}
}
err = mapFields(ctx, updatedVolume, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating volume", 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, "volume updated")
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *volumeResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from state
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
volumeId := model.VolumeId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "volume_id", volumeId)
// Delete existing volume
err := r.client.DeleteVolume(ctx, projectId, region, volumeId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting volume", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
_, err = wait.DeleteVolumeWaitHandler(ctx, r.client, projectId, region, volumeId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting volume", fmt.Sprintf("volume deletion waiting: %v", err))
return
}
tflog.Info(ctx, "volume deleted")
}
// ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,volume_id
func (r *volumeResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing volume",
fmt.Sprintf("Expected import identifier with format: [project_id],[region],[volume_id] Got: %q", req.ID),
)
return
}
ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": idParts[0],
"region": idParts[1],
"volume_id": idParts[2],
})
tflog.Info(ctx, "volume state imported")
}
func mapFields(ctx context.Context, volumeResp *iaas.Volume, model *Model, region string) error {
if volumeResp == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var volumeId string
if model.VolumeId.ValueString() != "" {
volumeId = model.VolumeId.ValueString()
} else if volumeResp.Id != nil {
volumeId = *volumeResp.Id
} else {
return fmt.Errorf("Volume id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, volumeId)
model.Region = types.StringValue(region)
labels, err := iaasUtils.MapLabels(ctx, volumeResp.Labels, model.Labels)
if err != nil {
return err
}
var sourceValues map[string]attr.Value
var sourceObject basetypes.ObjectValue
if volumeResp.Source == nil {
sourceObject = types.ObjectNull(sourceTypes)
} else {
sourceValues = map[string]attr.Value{
"type": types.StringPointerValue(volumeResp.Source.Type),
"id": types.StringPointerValue(volumeResp.Source.Id),
}
var diags diag.Diagnostics
sourceObject, diags = types.ObjectValue(sourceTypes, sourceValues)
if diags.HasError() {
return fmt.Errorf("creating source: %w", core.DiagsToError(diags))
}
}
model.VolumeId = types.StringValue(volumeId)
model.AvailabilityZone = types.StringPointerValue(volumeResp.AvailabilityZone)
model.Description = types.StringPointerValue(volumeResp.Description)
model.Name = types.StringPointerValue(volumeResp.Name)
// Workaround for volumes with no names which return an empty string instead of nil
if name := volumeResp.Name; name != nil && *name == "" {
model.Name = types.StringNull()
}
model.Labels = labels
model.PerformanceClass = types.StringPointerValue(volumeResp.PerformanceClass)
model.ServerId = types.StringPointerValue(volumeResp.ServerId)
model.Size = types.Int64PointerValue(volumeResp.Size)
model.Source = sourceObject
model.Encrypted = types.BoolPointerValue(volumeResp.Encrypted)
// no need to map encryption parameters as they are only **sent** to the API but **never returned**
return nil
}
func toCreatePayload(ctx context.Context, model *Model, source *sourceModel) (*iaas.CreateVolumePayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
labels, err := conversion.ToStringInterfaceMap(ctx, model.Labels)
if err != nil {
return nil, fmt.Errorf("converting to Go map: %w", err)
}
var sourcePayload *iaas.VolumeSource
if !source.Id.IsNull() && !source.Type.IsNull() {
sourcePayload = &iaas.VolumeSource{
Id: conversion.StringValueToPointer(source.Id),
Type: conversion.StringValueToPointer(source.Type),
}
}
payload := iaas.CreateVolumePayload{
AvailabilityZone: conversion.StringValueToPointer(model.AvailabilityZone),
Description: conversion.StringValueToPointer(model.Description),
Labels: &labels,
Name: conversion.StringValueToPointer(model.Name),
PerformanceClass: conversion.StringValueToPointer(model.PerformanceClass),
Size: conversion.Int64ValueToPointer(model.Size),
Source: sourcePayload,
}
if model.EncryptionParameters != nil {
var keyPayload *[]byte
if !utils.IsUndefined(model.EncryptionParameters.KeyPayloadBase64WriteOnly) {
keyPayload = sdkUtils.Ptr([]byte(model.EncryptionParameters.KeyPayloadBase64WriteOnly.ValueString()))
} else if !utils.IsUndefined(model.EncryptionParameters.KeyPayloadBase64) {
keyPayload = sdkUtils.Ptr([]byte(model.EncryptionParameters.KeyPayloadBase64.ValueString()))
}
payload.EncryptionParameters = &iaas.VolumeEncryptionParameter{
KekKeyId: conversion.StringValueToPointer(model.EncryptionParameters.KekKeyId),
KekKeyVersion: conversion.Int64ValueToPointer(model.EncryptionParameters.KekKeyVersion),
KekKeyringId: conversion.StringValueToPointer(model.EncryptionParameters.KekKeyringId),
KekProjectId: nil,
KeyPayload: keyPayload,
ServiceAccount: conversion.StringValueToPointer(model.EncryptionParameters.ServiceAccount),
}
}
return &payload, nil
}
func toUpdatePayload(ctx context.Context, model *Model, currentLabels types.Map) (*iaas.UpdateVolumePayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
labels, err := conversion.ToJSONMapPartialUpdatePayload(ctx, currentLabels, model.Labels)
if err != nil {
return nil, fmt.Errorf("converting to Go map: %w", err)
}
return &iaas.UpdateVolumePayload{
Description: conversion.StringValueToPointer(model.Description),
Name: conversion.StringValueToPointer(model.Name),
Labels: &labels,
}, nil
}