-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathresource_instance.go
More file actions
1641 lines (1466 loc) · 53.3 KB
/
Copy pathresource_instance.go
File metadata and controls
1641 lines (1466 loc) · 53.3 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package provider
import (
"context"
"fmt"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
"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/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/setplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"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-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/oxidecomputer/oxide.go/oxide"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = (*instanceResource)(nil)
_ resource.ResourceWithConfigure = (*instanceResource)(nil)
)
// NewInstanceResource is a helper function to simplify the provider implementation.
func NewInstanceResource() resource.Resource {
return &instanceResource{}
}
// instanceResource is the resource implementation.
type instanceResource struct {
client *oxide.Client
}
type instanceResourceModel struct {
AntiAffinityGroups types.Set `tfsdk:"anti_affinity_groups"`
BootDiskID types.String `tfsdk:"boot_disk_id"`
Description types.String `tfsdk:"description"`
DiskAttachments types.Set `tfsdk:"disk_attachments"`
ExternalIPs []instanceResourceExternalIPModel `tfsdk:"external_ips"`
HostName types.String `tfsdk:"host_name"`
ID types.String `tfsdk:"id"`
Memory types.Int64 `tfsdk:"memory"`
Name types.String `tfsdk:"name"`
NetworkInterfaces []instanceResourceNICModel `tfsdk:"network_interfaces"`
NCPUs types.Int64 `tfsdk:"ncpus"`
ProjectID types.String `tfsdk:"project_id"`
SSHPublicKeys types.Set `tfsdk:"ssh_public_keys"`
StartOnCreate types.Bool `tfsdk:"start_on_create"`
TimeCreated types.String `tfsdk:"time_created"`
TimeModified types.String `tfsdk:"time_modified"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
UserData types.String `tfsdk:"user_data"`
}
type instanceResourceNICModel struct {
Description types.String `tfsdk:"description"`
ID types.String `tfsdk:"id"`
IPAddr types.String `tfsdk:"ip_address"`
MAC types.String `tfsdk:"mac_address"`
Name types.String `tfsdk:"name"`
Primary types.Bool `tfsdk:"primary"`
SubnetID types.String `tfsdk:"subnet_id"`
TimeCreated types.String `tfsdk:"time_created"`
TimeModified types.String `tfsdk:"time_modified"`
VPCID types.String `tfsdk:"vpc_id"`
}
type instanceResourceExternalIPModel struct {
ID types.String `tfsdk:"id"`
Type types.String `tfsdk:"type"`
}
// Metadata returns the resource type name.
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = "oxide_instance"
}
// Configure adds the provider configured client to the data source.
func (r *instanceResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
r.client = req.ProviderData.(*oxide.Client)
}
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
// Schema defines the schema for the resource.
func (r *instanceResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"project_id": schema.StringAttribute{
Required: true,
Description: "ID of the project that will contain the instance.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"name": schema.StringAttribute{
Required: true,
Description: "Name of the instance.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"description": schema.StringAttribute{
Required: true,
Description: "Description for the instance.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"host_name": schema.StringAttribute{
Required: true,
Description: "Host name of the instance",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"memory": schema.Int64Attribute{
Required: true,
Description: "Instance memory in bytes.",
},
"ncpus": schema.Int64Attribute{
Required: true,
Description: "Number of CPUs allocated for this instance.",
},
"anti_affinity_groups": schema.SetAttribute{
Optional: true,
Description: "IDs of the anti-affinity groups this instance should belong to.",
ElementType: types.StringType,
},
"boot_disk_id": schema.StringAttribute{
Optional: true,
Description: "ID of the disk the instance should be booted from.",
Validators: []validator.String{
stringvalidator.AlsoRequires(
path.MatchRoot("disk_attachments"),
),
},
},
"start_on_create": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
Description: "Starts the instance on creation",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.RequiresReplaceIfConfigured(),
},
},
"disk_attachments": schema.SetAttribute{
Optional: true,
Description: "IDs of the disks to be attached to the instance.",
ElementType: types.StringType,
},
"ssh_public_keys": schema.SetAttribute{
Optional: true,
Description: "An allowlist of IDs of the SSH public keys to be transferred to the instance via cloud-init during instance creation.",
ElementType: types.StringType,
PlanModifiers: []planmodifier.Set{
setplanmodifier.RequiresReplace(),
},
Validators: []validator.Set{
setvalidator.NoNullValues(),
setvalidator.ValueStringsAre(
stringvalidator.NoneOf(""),
),
},
},
"network_interfaces": schema.SetNestedAttribute{
Optional: true,
Description: "Associated Network Interfaces.",
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Required: true,
Description: "Name of the instance network interface.",
// TODO: Remove once update is implemented
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIf(
RequiresReplaceUnlessEmptyStringOrNull(), "", "",
),
},
},
"description": schema.StringAttribute{
Required: true,
Description: "Description for the instance network interface.",
// TODO: Remove once update is implemented
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIf(
RequiresReplaceUnlessEmptyStringOrNull(), "", "",
),
},
},
"subnet_id": schema.StringAttribute{
Required: true,
Description: "ID of the VPC subnet in which to create the instance network interface.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIf(
RequiresReplaceUnlessEmptyStringOrNull(), "", "",
),
},
},
"vpc_id": schema.StringAttribute{
Required: true,
Description: "ID of the VPC in which to create the instance network interface",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIf(
RequiresReplaceUnlessEmptyStringOrNull(), "", "",
),
},
},
"ip_address": schema.StringAttribute{
Optional: true,
Computed: true,
Description: "IP address for the instance network interface. " +
"One will be auto-assigned if not provided.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIfConfigured(),
},
},
"mac_address": schema.StringAttribute{
Computed: true,
Description: "MAC address assigned to the instance network interface.",
},
"id": schema.StringAttribute{
Computed: true,
Description: "Unique, immutable, system-controlled identifier of the instance network interface.",
},
"primary": schema.BoolAttribute{
Computed: true,
Description: "True if this is the primary network interface for the instance to which it's attached to.",
},
"time_created": schema.StringAttribute{
Computed: true,
Description: "Timestamp of when this instance network interface was created.",
},
"time_modified": schema.StringAttribute{
Computed: true,
Description: "Timestamp of when this instance network interface was last modified.",
},
},
},
},
"external_ips": schema.SetNestedAttribute{
Optional: true,
Description: "External IP addresses provided to this instance.",
Validators: []validator.Set{
instanceExternalIPValidator{},
},
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
// The id attribute is optional, computed, and has a default to account for the
// case where an instance created with an external IP using the default IP pool
// (i.e., id = null) would drift when read (e.g., id = "") and require updating
// in place.
"id": schema.StringAttribute{
Description: "If type is ephemeral, ID of the IP pool to retrieve addresses from, or all available pools if not specified. If type is floating, ID of the floating IP",
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
},
"type": schema.StringAttribute{
Description: "Type of external IP.",
Required: true,
Validators: []validator.String{
stringvalidator.OneOf(
string(oxide.ExternalIpCreateTypeEphemeral),
string(oxide.ExternalIpCreateTypeFloating),
),
},
},
},
},
},
"user_data": schema.StringAttribute{
Optional: true,
Description: "User data for instance initialization systems (such as cloud-init). " +
"Must be a Base64-encoded string, as specified in RFC 4648 § 4 (+ and / characters with padding). " +
"Maximum 32 KiB unencoded data.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"timeouts": timeouts.Attributes(ctx, timeouts.Opts{
Create: true,
Read: true,
Update: true,
Delete: true,
}),
"id": schema.StringAttribute{
Computed: true,
Description: "Unique, immutable, system-controlled identifier of the instance.",
},
"time_created": schema.StringAttribute{
Computed: true,
Description: "Timestamp of when this instance was created.",
},
"time_modified": schema.StringAttribute{
Computed: true,
Description: "Timestamp of when this instance was last modified.",
},
},
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan instanceResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
createTimeout, diags := plan.Timeouts.Create(ctx, defaultTimeout())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, createTimeout)
defer cancel()
params := oxide.InstanceCreateParams{
Project: oxide.NameOrId(plan.ProjectID.ValueString()),
Body: &oxide.InstanceCreate{
Description: plan.Description.ValueString(),
Name: oxide.Name(plan.Name.ValueString()),
Hostname: oxide.Hostname(plan.HostName.ValueString()),
Memory: oxide.ByteCount(plan.Memory.ValueInt64()),
Ncpus: oxide.InstanceCpuCount(plan.NCPUs.ValueInt64()),
Start: plan.StartOnCreate.ValueBoolPointer(),
UserData: plan.UserData.ValueString(),
},
}
// Add boot disk if any
if !plan.BootDiskID.IsNull() {
// Validate whether the boot disk ID is included in `attachments`
// This is necessary as the response from InstanceDiskList includes
// the boot disk and would result in an inconsistent state in terraform
isBootIDPresent, err := attrValueSliceContains(plan.DiskAttachments.Elements(), plan.BootDiskID.ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Error unquoting disk attachments",
"Validation error: "+err.Error(),
)
return
}
if !isBootIDPresent {
resp.Diagnostics.AddError(
"Validation error",
"Boot disk ID should be part of `disk_attachments`",
)
return
}
diskParams := oxide.DiskViewParams{
Disk: oxide.NameOrId(plan.BootDiskID.ValueString()),
}
diskView, err := r.client.DiskView(ctx, diskParams)
if err != nil {
resp.Diagnostics.AddError(
"Error retrieving boot disk information",
"API error: "+err.Error(),
)
return
}
params.Body.BootDisk = &oxide.InstanceDiskAttachment{
Name: diskView.Name,
Type: oxide.InstanceDiskAttachmentTypeAttach,
}
}
sshKeys, diags := newNameOrIdList(plan.SSHPublicKeys)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
params.Body.SshPublicKeys = sshKeys
antiAffinityGroupIDs, diags := newNameOrIdList(plan.AntiAffinityGroups)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
params.Body.AntiAffinityGroups = antiAffinityGroupIDs
disks, diags := newDiskAttachmentsOnCreate(ctx, r.client, plan.DiskAttachments)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// The control plane API counts the BootDisk and the Disk attachments when it calculates the limit on disk attachments.
// If bootdisk is set explicitly, we don't want it to be in the API call, but we need it in the state entry.
params.Body.Disks = filterBootDiskFromDisks(disks, params.Body.BootDisk)
externalIPs := newExternalIPsOnCreate(plan.ExternalIPs)
params.Body.ExternalIps = externalIPs
nics, diags := newNetworkInterfaceAttachment(ctx, r.client, plan.NetworkInterfaces)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
params.Body.NetworkInterfaces = nics
instance, err := r.client.InstanceCreate(ctx, params)
if err != nil {
resp.Diagnostics.AddError(
"Error creating instance",
"API error: "+err.Error(),
)
return
}
tflog.Trace(ctx, fmt.Sprintf("created instance with ID: %v", instance.Id), map[string]any{"success": true})
// Map response body to schema and populate Computed attribute values
plan.ID = types.StringValue(instance.Id)
plan.TimeCreated = types.StringValue(instance.TimeCreated.String())
plan.TimeModified = types.StringValue(instance.TimeModified.String())
// Populate NIC information
for i := range plan.NetworkInterfaces {
params := oxide.InstanceNetworkInterfaceViewParams{
Interface: oxide.NameOrId(plan.NetworkInterfaces[i].Name.ValueString()),
Instance: oxide.NameOrId(instance.Id),
}
nic, err := r.client.InstanceNetworkInterfaceView(ctx, params)
if err != nil {
resp.Diagnostics.AddError(
"Unable to read instance network interface:",
"API error: "+err.Error(),
)
// Don't return here as the instance has already been created.
// Otherwise the state won't be saved.
continue
}
tflog.Trace(ctx, fmt.Sprintf("read instance network interface with ID: %v", nic.Id), map[string]any{"success": true})
// Map response body to schema and populate Computed attribute values
plan.NetworkInterfaces[i].ID = types.StringValue(nic.Id)
plan.NetworkInterfaces[i].TimeCreated = types.StringValue(nic.TimeCreated.String())
plan.NetworkInterfaces[i].TimeModified = types.StringValue(nic.TimeModified.String())
plan.NetworkInterfaces[i].MAC = types.StringValue(string(nic.Mac))
plan.NetworkInterfaces[i].Primary = types.BoolPointerValue(nic.Primary)
// Setting IPAddress as it is both computed and optional
plan.NetworkInterfaces[i].IPAddr = types.StringValue(nic.Ip)
}
// Save plan into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
}
// Read refreshes the Terraform state with the latest data.
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state instanceResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
readTimeout, diags := state.Timeouts.Read(ctx, defaultTimeout())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
params := oxide.InstanceViewParams{
Instance: oxide.NameOrId(state.ID.ValueString()),
}
instance, err := r.client.InstanceView(ctx, params)
if err != nil {
if is404(err) {
// Remove resource from state during a refresh
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError(
"Unable to read instance:",
"API error: "+err.Error(),
)
return
}
tflog.Trace(ctx, fmt.Sprintf("read instance with ID: %v", instance.Id), map[string]any{"success": true})
if instance.BootDiskId != "" {
state.BootDiskID = types.StringValue(instance.BootDiskId)
}
state.Description = types.StringValue(instance.Description)
state.HostName = types.StringValue(string(instance.Hostname))
state.ID = types.StringValue(instance.Id)
state.Memory = types.Int64Value(int64(instance.Memory))
state.Name = types.StringValue(string(instance.Name))
state.NCPUs = types.Int64Value(int64(instance.Ncpus))
state.ProjectID = types.StringValue(instance.ProjectId)
state.TimeCreated = types.StringValue(instance.TimeCreated.String())
state.TimeModified = types.StringValue(instance.TimeModified.String())
externalIPs, diags := newAttachedExternalIPModel(ctx, r.client, state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Only set the external IPs if there are any to avoid drift.
if len(externalIPs) > 0 {
state.ExternalIPs = externalIPs
}
keySet, diags := newAssociatedSSHKeysOnCreateSet(ctx, r.client, state.ID.ValueString())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Only set the SSH key list if there are any associated keys
if len(keySet.Elements()) > 0 {
state.SSHPublicKeys = keySet
}
antiAffinityGroupSet, diags := newAssociatedAntiAffinityGroupsOnCreateSet(ctx, r.client, state.ID.ValueString())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Only set the anti-affinity group list if there are any associated groups
if len(antiAffinityGroupSet.Elements()) > 0 {
state.AntiAffinityGroups = antiAffinityGroupSet
}
diskSet, diags := newAttachedDisksSet(ctx, r.client, state.ID.ValueString())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Only set the disk list if there are disk attachments
if len(diskSet.Elements()) > 0 {
state.DiskAttachments = diskSet
}
nicSet, diags := newAttachedNetworkInterfacesModel(ctx, r.client, state.ID.ValueString())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Only populate NICs if there are associated NICs to avoid drift
if len(nicSet) > 0 {
state.NetworkInterfaces = nicSet
}
// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan instanceResourceModel
var state instanceResourceModel
// Read Terraform plan data into the plan model
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
// Read Terraform prior state data into the state model to retrieve ID
// which is a computed attribute, so it won't show up in the plan.
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
updateTimeout, diags := state.Timeouts.Update(ctx, defaultTimeout())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, updateTimeout)
defer cancel()
// The instance must be stopped for all updates
stopParams := oxide.InstanceStopParams{
Instance: oxide.NameOrId(state.ID.ValueString()),
}
_, err := r.client.InstanceStop(ctx, stopParams)
if err != nil {
if !is404(err) {
resp.Diagnostics.AddError(
"Unable to stop instance:",
"API error: "+err.Error(),
)
return
}
}
diags = waitForInstanceStop(ctx, r.client, updateTimeout, state.ID.ValueString())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Trace(ctx, fmt.Sprintf("stopped instance with ID: %v", state.ID.ValueString()), map[string]any{"success": true})
// Update external IPs.
// We detach external IPs first to account for the case where an ephemeral
// external IP's IP Pool is modified. This is because there can only be one
// ephemeral external IP attached to an instance at a given time and the
// last detachment/attachment wins.
{
externalIPsToDetach := sliceDiff(state.ExternalIPs, plan.ExternalIPs)
resp.Diagnostics.Append(detachExternalIPs(ctx, r.client, externalIPsToDetach, state.ID.ValueString())...)
if resp.Diagnostics.HasError() {
return
}
externalIPsToAttach := sliceDiff(plan.ExternalIPs, state.ExternalIPs)
resp.Diagnostics.Append(attachExternalIPs(ctx, r.client, externalIPsToAttach, state.ID.ValueString())...)
if resp.Diagnostics.HasError() {
return
}
}
// Update disk attachments
//
// We attach new disks first in case the new boot disk is one of the newly added
// disks
planDisks := plan.DiskAttachments.Elements()
stateDisks := state.DiskAttachments.Elements()
// Check plan and if it has an ID that the state doesn't then attach it
disksToAttach := sliceDiff(planDisks, stateDisks)
resp.Diagnostics.Append(attachDisks(ctx, r.client, disksToAttach, state.ID.ValueString())...)
if resp.Diagnostics.HasError() {
return
}
// Update instance only if configurable instance params change.
// Due to the design of the API, when updating an instance all
// parameters must be set. This means we set all of the parameters
// even if only a single one changed.
if state.BootDiskID != plan.BootDiskID ||
state.Memory != plan.Memory ||
state.NCPUs != plan.NCPUs {
params := oxide.InstanceUpdateParams{
Instance: oxide.NameOrId(state.ID.ValueString()),
Body: &oxide.InstanceUpdate{
BootDisk: oxide.NameOrId(plan.BootDiskID.ValueString()),
Memory: oxide.ByteCount(plan.Memory.ValueInt64()),
Ncpus: oxide.InstanceCpuCount(plan.NCPUs.ValueInt64()),
},
}
instance, err := r.client.InstanceUpdate(ctx, params)
if err != nil {
resp.Diagnostics.AddError(
"Unable to read instance:",
"API error: "+err.Error(),
)
return
}
tflog.Trace(ctx, fmt.Sprintf(
"updated boot disk forinstance with ID: %v", instance.Id), map[string]any{"success": true},
)
}
// Check state and if it has an ID that the plan doesn't then detach it
//
// We only detach disks once we have made changes to the boot disk (if any)
// in case we need to remove the previous boot disk
disksToDetach := sliceDiff(stateDisks, planDisks)
resp.Diagnostics.Append(detachDisks(ctx, r.client, disksToDetach, state.ID.ValueString())...)
if resp.Diagnostics.HasError() {
return
}
// Update NICs
planNICs := plan.NetworkInterfaces
stateNICs := state.NetworkInterfaces
// Check plan and if it has an ID that the state doesn't then attach it
nicsToCreate := sliceDiff(planNICs, stateNICs)
resp.Diagnostics.Append(createNICs(ctx, r.client, nicsToCreate, state.ID.ValueString())...)
if resp.Diagnostics.HasError() {
return
}
// Check state and if it has an ID that the plan doesn't then delete it
nicsToDelete := sliceDiff(stateNICs, planNICs)
resp.Diagnostics.Append(deleteNICs(ctx, r.client, nicsToDelete)...)
if resp.Diagnostics.HasError() {
return
}
// Update anti-affinity groups
planAntiAffinityGroups := plan.AntiAffinityGroups.Elements()
stateAntiAffinityGroups := state.AntiAffinityGroups.Elements()
// Check plan and if it has an ID that the state doesn't then add it
antiAffinityGroupsToAdd := sliceDiff(planAntiAffinityGroups, stateAntiAffinityGroups)
resp.Diagnostics.Append(addAntiAffinityGroups(ctx, r.client, antiAffinityGroupsToAdd, state.ID.ValueString())...)
if resp.Diagnostics.HasError() {
return
}
// Check state and if it has an ID that the plan doesn't then remove it
antiAffinityGroupsToRemove := sliceDiff(stateAntiAffinityGroups, planAntiAffinityGroups)
resp.Diagnostics.Append(removeAntiAffinityGroups(ctx, r.client, antiAffinityGroupsToRemove, state.ID.ValueString())...)
if resp.Diagnostics.HasError() {
return
}
startParams := oxide.InstanceStartParams{Instance: oxide.NameOrId(state.ID.ValueString())}
_, err = r.client.InstanceStart(ctx, startParams)
if err != nil {
if !is404(err) {
resp.Diagnostics.AddError(
"Unable to start instance:",
"API error: "+err.Error(),
)
return
}
}
// Read instance to retrieve modified time value if this is the only update we are doing
params := oxide.InstanceViewParams{
Instance: oxide.NameOrId(state.ID.ValueString()),
}
instance, err := r.client.InstanceView(ctx, params)
if err != nil {
resp.Diagnostics.AddError(
"Unable to read instance:",
"API error: "+err.Error(),
)
return
}
tflog.Trace(ctx, fmt.Sprintf("read instance with ID: %v", instance.Id), map[string]any{"success": true})
// Map response body to schema and populate Computed attribute values
plan.ID = types.StringValue(instance.Id)
plan.ProjectID = types.StringValue(instance.ProjectId)
plan.TimeCreated = types.StringValue(instance.TimeCreated.String())
plan.TimeModified = types.StringValue(instance.TimeModified.String())
// We use the plan here instead of the state to capture the desired IP pool ID
// value for the ephemeral external IP rather than the previous value.
externalIPs, diags := newAttachedExternalIPModel(ctx, r.client, plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
if len(externalIPs) > 0 {
plan.ExternalIPs = externalIPs
}
// TODO: should I do this or read from the newly created ones?
diskSet, diags := newAttachedDisksSet(ctx, r.client, state.ID.ValueString())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Only set the disk list if there are disk attachments
if len(diskSet.Elements()) > 0 {
plan.DiskAttachments = diskSet
}
// TODO: should I do this or read from the newly created ones?
nicModel, diags := newAttachedNetworkInterfacesModel(ctx, r.client, state.ID.ValueString())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Only populate NICs if there are associated NICs to avoid drift
if len(nicModel) > 0 {
plan.NetworkInterfaces = nicModel
}
// Save plan into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state instanceResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
deleteTimeout, diags := state.Timeouts.Delete(ctx, defaultTimeout())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, deleteTimeout)
defer cancel()
params := oxide.InstanceStopParams{
Instance: oxide.NameOrId(state.ID.ValueString()),
}
_, err := r.client.InstanceStop(ctx, params)
if err != nil {
if !is404(err) {
resp.Diagnostics.AddError(
"Unable to stop instance:",
"API error: "+err.Error(),
)
return
}
}
diags = waitForInstanceStop(ctx, r.client, deleteTimeout, state.ID.ValueString())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Trace(ctx, fmt.Sprintf("stopped instance with ID: %v", state.ID.ValueString()), map[string]any{"success": true})
params2 := oxide.InstanceDeleteParams{
Instance: oxide.NameOrId(state.ID.ValueString()),
}
if err := r.client.InstanceDelete(ctx, params2); err != nil {
if !is404(err) {
resp.Diagnostics.AddError(
"Unable to delete instance:",
"API error: "+err.Error(),
)
return
}
}
tflog.Trace(ctx, fmt.Sprintf("deleted instance with ID: %v", state.ID.ValueString()), map[string]any{"success": true})
}
func waitForInstanceStop(ctx context.Context, client *oxide.Client, timeout time.Duration, instanceID string) diag.Diagnostics {
var diags diag.Diagnostics
stateConfig := retry.StateChangeConf{
PollInterval: time.Second,
Delay: time.Second,
Pending: []string{
string(oxide.InstanceStateCreating),
string(oxide.InstanceStateStarting),
string(oxide.InstanceStateRunning),
string(oxide.InstanceStateStopping),
string(oxide.InstanceStateRebooting),
string(oxide.InstanceStateMigrating),
string(oxide.InstanceStateRepairing),
},
Target: []string{string(oxide.InstanceStateStopped)},
Timeout: timeout,
Refresh: func() (interface{}, string, error) {
tflog.Info(ctx, fmt.Sprintf("checking on state of instance: %v", instanceID))
params := oxide.InstanceViewParams{
Instance: oxide.NameOrId(instanceID),
}
instance, err := client.InstanceView(ctx, params)
if err != nil {
if !is404(err) {
return nil, "nil", fmt.Errorf("while polling for the status of instance %v: %v", instanceID, err)
}
return instance, "", nil
}
tflog.Trace(ctx, fmt.Sprintf("read instance with ID: %v", instanceID), map[string]any{"success": true})
return instance, string(instance.RunState), nil
},
}
if _, err := stateConfig.WaitForStateContext(ctx); err != nil {
if !is404(err) {
diags.AddError(
"Error stopping instance",
"API error: "+err.Error(),
)
}
return diags
}
return nil
}
func newAttachedDisksSet(ctx context.Context, client *oxide.Client, instanceID string) (types.Set, diag.Diagnostics) {
var diags diag.Diagnostics
params := oxide.InstanceDiskListParams{
Limit: oxide.NewPointer(1000000000),
Instance: oxide.NameOrId(instanceID),
}
disks, err := client.InstanceDiskList(ctx, params)
if err != nil {
diags.AddError(
"Unable to list attached disks:",
"API error: "+err.Error(),
)
return types.SetNull(types.StringType), diags
}
d := []attr.Value{}
for _, disk := range disks.Items {
id := types.StringValue(disk.Id)
d = append(d, id)
}
diskSet, diags := types.SetValue(types.StringType, d)
diags.Append(diags...)
if diags.HasError() {
return types.SetNull(types.StringType), diags
}
return diskSet, nil
}
func newAssociatedSSHKeysOnCreateSet(ctx context.Context, client *oxide.Client, instanceID string) (types.Set, diag.Diagnostics) {
var diags diag.Diagnostics
params := oxide.InstanceSshPublicKeyListParams{
Limit: oxide.NewPointer(1000000000),
Instance: oxide.NameOrId(instanceID),
}
keys, err := client.InstanceSshPublicKeyList(ctx, params)
if err != nil {
diags.AddError(
"Unable to list associated SSH keys:",
"API error: "+err.Error(),
)
return types.SetNull(types.StringType), diags
}
d := []attr.Value{}
for _, key := range keys.Items {
id := types.StringValue(key.Id)
d = append(d, id)
}
keySet, diags := types.SetValue(types.StringType, d)
diags.Append(diags...)
if diags.HasError() {
return types.SetNull(types.StringType), diags
}
return keySet, nil
}
func newAssociatedAntiAffinityGroupsOnCreateSet(ctx context.Context, client *oxide.Client, instanceID string) (types.Set, diag.Diagnostics) {
var diags diag.Diagnostics
params := oxide.InstanceAntiAffinityGroupListParams{
Limit: oxide.NewPointer(1000000000),
Instance: oxide.NameOrId(instanceID),
}
groups, err := client.InstanceAntiAffinityGroupList(ctx, params)
if err != nil {
diags.AddError(
"Unable to list associated anti-affinity groups:",
"API error: "+err.Error(),
)
return types.SetNull(types.StringType), diags
}
d := []attr.Value{}
for _, group := range groups.Items {
id := types.StringValue(group.Id)
d = append(d, id)
}
groupSet, diags := types.SetValue(types.StringType, d)
diags.Append(diags...)
if diags.HasError() {