-
Notifications
You must be signed in to change notification settings - Fork 21
/
resource_server.go
1596 lines (1442 loc) · 52.8 KB
/
resource_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ionoscloud
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services/cloudapi"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services/cloudapi/cloudapifirewall"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services/cloudapi/cloudapinic"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services/cloudapi/cloudapiserver"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/slice"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/utils/constant"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
ionoscloud "github.com/ionos-cloud/sdk-go/v6"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/utils"
)
func resourceServer() *schema.Resource {
return &schema.Resource{
CreateContext: resourceServerCreate,
ReadContext: resourceServerRead,
UpdateContext: resourceServerUpdate,
DeleteContext: resourceServerDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceServerImport,
},
CustomizeDiff: checkServerImmutableFields,
Schema: map[string]*schema.Schema{
"template_uuid": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
"cores": {
Type: schema.TypeInt,
Optional: true, // this should be required when the deprecated version will be removed
Computed: true,
},
"ram": {
Type: schema.TypeInt,
Optional: true, // this should be required when the deprecated version will be removed
Computed: true,
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"AUTO", "ZONE_1", "ZONE_2"}, true)),
},
"boot_volume": {
Type: schema.TypeString,
Computed: true,
},
"boot_cdrom": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Please use the 'ionoscloud_server_boot_device_selection' resource for managing the boot device of the server.",
ValidateDiagFunc: validation.ToDiagFunc(validation.IsUUID),
Description: "The associated boot drive, if any. Must be the UUID of a bootable CDROM image that you can retrieve using the image data source",
},
"cpu_family": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "server usages: ENTERPRISE or CUBE",
DiffSuppressFunc: utils.DiffToLower,
//to do: add in next release
//ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"CUBE", "ENTERPRISE"}, true)),
},
"boot_image": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"primary_nic": {
Type: schema.TypeString,
Computed: true,
Description: "Id of the primary network interface",
},
"primary_ip": {
Type: schema.TypeString,
Computed: true,
},
"firewallrule_id": {
Type: schema.TypeString,
Computed: true,
},
"firewallrule_ids": {
Type: schema.TypeList,
Optional: true,
Computed: true,
ConfigMode: schema.SchemaConfigModeAttr,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"datacenter_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
"image_password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
Computed: true,
ConflictsWith: []string{"volume.0.image_password"},
},
"image_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"ssh_key_path": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
ConflictsWith: []string{"volume.0.ssh_key_path", "volume.0.ssh_keys", "ssh_keys"},
Optional: true,
Deprecated: "Will be renamed to ssh_keys in the future, to allow users to set both the ssh key path or directly the ssh key",
Description: "Immutable List of absolute or relative paths to files containing public SSH key that will be injected into IonosCloud provided Linux images. Does not support `~` expansion to homedir in the given path. Public SSH keys are set on the image as authorized keys for appropriate SSH login to the instance using the corresponding private key. This field may only be set in creation requests. When reading, it always returns null. SSH keys are only supported if a public Linux image is used for the volume creation. This property is immutable.",
},
"ssh_keys": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
ConflictsWith: []string{"volume.0.ssh_key_path", "volume.0.ssh_keys", "ssh_key_path"},
Optional: true,
Description: "Public SSH keys are set on the image as authorized keys for appropriate SSH login to the instance using the corresponding private key. This field may only be set in creation requests. When reading, it always returns null. SSH keys are only supported if a public Linux image is used for the volume creation.",
//todo: remove as test servervassic fails
//DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// if k == "ssh_keys.#" {
// if d.Get("volume.0.ssh_keys.#") == new {
// return true
// }
// }
//
// sshKeys := d.Get("volume.0.ssh_keys").([]interface{})
// oldSshKeys := d.Get("ssh_keys").([]interface{})
//
// if len(utils.DiffSlice(slice.AnyToString(sshKeys), slice.AnyToString(oldSshKeys))) == 0 {
// return true
// }
//
// return false
//},
},
"volume": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The size of the volume in GB.",
},
"disk_type": {
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
"image_password": {
Type: schema.TypeString,
Optional: true,
Deprecated: "Please use image_password under server level",
ConflictsWith: []string{"image_password"},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if d.Get("image_password").(string) == new {
return true
}
return false
},
},
"licence_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"ssh_key_path": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Deprecated: "Please use ssh_key_path under server level",
Description: "Public SSH keys are set on the image as authorized keys for appropriate SSH login to the instance using the corresponding private key. This field may only be set in creation requests. When reading, it always returns null. SSH keys are only supported if a public Linux image is used for the volume creation.",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if k == "volume.0.ssh_key_path.#" {
if d.Get("ssh_key_path.#") == new {
return true
}
}
sshKeyPath := d.Get("volume.0.ssh_key_path").([]interface{})
oldSshKeyPath := d.Get("ssh_key_path").([]interface{})
difKeypath := slice.DiffString(slice.AnyToString(sshKeyPath), slice.AnyToString(oldSshKeyPath))
if len(difKeypath) == 0 {
return true
}
return false
},
},
"ssh_keys": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Deprecated: "Please use ssh_keys under server level",
Computed: true,
ForceNew: true,
Description: "Public SSH keys are set on the image as authorized keys for appropriate SSH login to the instance using the corresponding private key. This field may only be set in creation requests. When reading, it always returns null. SSH keys are only supported if a public Linux image is used for the volume creation.",
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
if k == "volume.0.ssh_keys.#" {
if d.Get("ssh_keys.#") == new {
return true
}
}
sshKeys := d.Get("volume.0.ssh_keys").([]interface{})
oldSshKeys := d.Get("ssh_keys").([]interface{})
if len(slice.DiffString(slice.AnyToString(sshKeys), slice.AnyToString(oldSshKeys))) == 0 {
return true
}
return false
},
},
"bus": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"availability_zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"AUTO", "ZONE_1", "ZONE_2", "ZONE_3"}, true)),
},
"cpu_hot_plug": {
Type: schema.TypeBool,
Computed: true,
},
"ram_hot_plug": {
Type: schema.TypeBool,
Computed: true,
},
"nic_hot_plug": {
Type: schema.TypeBool,
Computed: true,
},
"nic_hot_unplug": {
Type: schema.TypeBool,
Computed: true,
},
"disc_virtio_hot_plug": {
Type: schema.TypeBool,
Computed: true,
},
"disc_virtio_hot_unplug": {
Type: schema.TypeBool,
Computed: true,
},
"device_number": {
Type: schema.TypeInt,
Computed: true,
},
"backup_unit_id": {
Type: schema.TypeString,
Description: "The uuid of the Backup Unit that user has access to. The property is immutable and is only allowed to be set on a new volume creation. It is mandatory to provide either 'public image' or 'imageAlias' in conjunction with this property.",
Optional: true,
Computed: true,
},
"user_data": {
Type: schema.TypeString,
Description: "The cloud-init configuration for the volume as base64 encoded string. The property is immutable and is only allowed to be set on a new volume creation. It is mandatory to provide either 'public image' or 'imageAlias' that has cloud-init compatibility in conjunction with this property.",
Optional: true,
Computed: true,
},
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
},
"boot_server": {
Type: schema.TypeString,
Description: "The UUID of the attached server.",
Computed: true,
},
},
},
},
"vm_state": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Sets the power state of the server. Possible values: `RUNNING`, `SHUTOFF` or `SUSPENDED`. SUSPENDED state is only valid for cube. SHUTOFF state is only valid for enterprise",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{constant.VMStateStart, constant.VMStateStop, constant.CubeVMStateStop}, true)),
},
"nic": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"mac": {
Type: schema.TypeString,
Computed: true,
},
"lan": {
Type: schema.TypeInt,
Required: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"dhcp": {
Type: schema.TypeBool,
Optional: true,
},
"dhcpv6": {
Type: schema.TypeBool,
Optional: true,
Description: "Indicates whether this NIC receives an IPv6 address through DHCP.",
},
"ipv6_cidr_block": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "IPv6 CIDR block assigned to the NIC.",
},
"ips": {
Type: schema.TypeList,
Elem: &schema.Schema{
Type: schema.TypeString,
DiffSuppressFunc: utils.DiffEmptyIps,
},
Description: "Collection of IP addresses assigned to a nic. Explicitly assigned public IPs need to come from reserved IP blocks, Passing value null or empty array will assign an IP address automatically.",
Computed: true,
Optional: true,
},
"ipv6_ips": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
Description: "Collection for IPv6 addresses assigned to a nic. Explicitly assigned IPv6 addresses need to come from inside the IPv6 CIDR block assigned to the nic.",
},
"firewall_active": {
Type: schema.TypeBool,
Optional: true,
},
"firewall_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"device_number": {
Type: schema.TypeInt,
Computed: true,
},
"pci_slot": {
Type: schema.TypeInt,
Computed: true,
},
"firewall": {
Description: "Firewall rules created in the server resource. The rules can also be created as separate resources outside the server resource",
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"protocol": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: utils.DiffToLower,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
"source_mac": {
Type: schema.TypeString,
Optional: true,
},
"source_ip": {
Type: schema.TypeString,
Optional: true,
},
"target_ip": {
Type: schema.TypeString,
Optional: true,
},
"port_range_start": {
Type: schema.TypeInt,
Optional: true,
ValidateDiagFunc: validation.ToDiagFunc(func(v interface{}, k string) (ws []string, errors []error) {
if v.(int) < 1 && v.(int) > 65534 {
errors = append(errors, fmt.Errorf("port start range must be between 1 and 65534"))
}
return
}),
},
"port_range_end": {
Type: schema.TypeInt,
Optional: true,
ValidateDiagFunc: validation.ToDiagFunc(func(v interface{}, k string) (ws []string, errors []error) {
if v.(int) < 1 && v.(int) > 65534 {
errors = append(errors, fmt.Errorf("port end range must be between 1 and 65534"))
}
return
}),
},
"icmp_type": {
Type: schema.TypeString,
Optional: true,
},
"icmp_code": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
},
},
},
"label": {
Type: schema.TypeSet,
Optional: true,
Elem: labelResource,
},
// When deleting the server, we need to delete the volume that was defined INSIDE the
// server resource. The only way to know which volume was defined INSIDE the server
// resource is to save the volume ID in this list.
// NOTE: In the current version, v6.3.6, it is required to define one volume (and only
// one) inside the server resource, but in the future we consider the possibility of
// adding more volumes within the server resource, in which case the current code should
// be revised as changes should also be made for the update function, as the list of
// inline_volume_ids can be modified.
"inline_volume_ids": {
Type: schema.TypeList,
Description: "A list that contains the IDs for the volumes defined inside the server resource.",
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
Timeouts: &resourceDefaultTimeouts,
}
}
func checkServerImmutableFields(_ context.Context, diff *schema.ResourceDiff, _ interface{}) error {
//we do not want to check in case of resource creation
if diff.Id() == "" {
return nil
}
if diff.HasChange("image_name") {
return fmt.Errorf("image_name %s", ImmutableError)
}
if diff.HasChange("availability_zone") {
return fmt.Errorf("availability_zone %s", ImmutableError)
}
if diff.HasChange("volume") {
if diff.HasChange("volume.0.user_data") {
return fmt.Errorf("volume.0.user_data %s", ImmutableError)
}
if diff.HasChange("volume.0.backup_unit_id") {
return fmt.Errorf("volume.0.backup_unit_id %s", ImmutableError)
}
if diff.HasChange("volume.0.disk_type") {
return fmt.Errorf("volume.0.disk_type %s", ImmutableError)
}
if diff.HasChange("volume.0.availability_zone") {
return fmt.Errorf("volume.0.availability_zone %s", ImmutableError)
}
}
return nil
}
func resourceServerCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
datacenterId := d.Get("datacenter_id").(string)
serverReq, err := initializeCreateRequests(d)
if err != nil {
diags := diag.FromErr(err)
return diags
}
serverType := d.Get("type").(string)
// create volume object with data to be used for image
volume, err := getVolumeData(d, "volume.0.", serverType)
if err != nil {
return diag.FromErr(err)
}
// get image and imageAlias
image, imageAlias, err := getImage(ctx, client, d, *volume)
if err != nil {
return diag.FromErr(err)
}
// add remaining properties in volume (dependent in image and imageAlias)
if imageAlias != "" {
volume.ImageAlias = &imageAlias
} else {
volume.ImageAlias = nil
}
if image != "" {
volume.Image = &image
} else {
volume.Image = nil
}
if backupUnitId, ok := d.GetOk("volume.0.backup_unit_id"); ok {
if utils.IsValidUUID(backupUnitId.(string)) {
if image == "" && imageAlias == "" {
diags := diag.FromErr(fmt.Errorf("it is mandatory to provide either public image or imageAlias in conjunction with backup unit id property"))
return diags
} else {
backupUnitId := backupUnitId.(string)
volume.BackupunitId = &backupUnitId
}
}
}
if userData, ok := d.GetOk("volume.0.user_data"); ok {
if image == "" && imageAlias == "" {
diags := diag.FromErr(fmt.Errorf("it is mandatory to provide either public image or imageAlias that has cloud-init compatibility in conjunction with backup unit id property "))
return diags
} else {
userData := userData.(string)
volume.UserData = &userData
}
}
// add volume object to serverReq
serverReq.Entities = &ionoscloud.ServerEntities{
Volumes: &ionoscloud.AttachedVolumes{
Items: &[]ionoscloud.Volume{
{
Properties: volume,
},
},
},
}
// get nic data and add object to serverReq
if nics, ok := d.GetOk("nic"); ok {
serverReq.Entities.Nics = &ionoscloud.Nics{
Items: &[]ionoscloud.Nic{},
}
if nics.([]interface{}) != nil {
for nicIndex := range nics.([]interface{}) {
nicPath := fmt.Sprintf("nic.%d.", nicIndex)
nic, err := cloudapinic.GetNicFromSchema(d, nicPath)
if err != nil {
diags := diag.FromErr(fmt.Errorf("create error occured while getting nic from schema: %w", err))
return diags
}
*serverReq.Entities.Nics.Items = append(*serverReq.Entities.Nics.Items, nic)
fwRulesPath := nicPath + "firewall"
if firewallRules, ok := d.GetOk(fwRulesPath); ok {
fwRules := []ionoscloud.FirewallRule{}
(*serverReq.Entities.Nics.Items)[nicIndex].Entities = &ionoscloud.NicEntities{
Firewallrules: &ionoscloud.FirewallRules{
Items: &[]ionoscloud.FirewallRule{},
},
}
if firewallRules.([]interface{}) != nil && len(firewallRules.([]interface{})) > 0 {
fwRulesIntf := firewallRules.([]interface{})
fwRulesProperties := make([]ionoscloud.FirewallruleProperties, len(fwRulesIntf))
err = utils.DecodeInterfaceToStruct(fwRulesIntf, fwRulesProperties)
if err != nil {
return diag.FromErr(fmt.Errorf("could not decode from %+v to slice of firewall rules %w", fwRulesIntf, err))
}
for idx := range fwRulesProperties {
cloudapifirewall.PropUnsetSetFieldIfNotSetInSchema(&fwRulesProperties[idx], fwRulesPath, d)
firewall := ionoscloud.FirewallRule{
Properties: &fwRulesProperties[idx],
}
fwRules = append(fwRules, firewall)
}
}
*(*serverReq.Entities.Nics.Items)[nicIndex].Entities.Firewallrules.Items = fwRules
}
}
}
}
postServer, apiResponse, err := client.ServersApi.DatacentersServersPost(ctx, datacenterId).Server(serverReq).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("error creating server: (%w)", err))
return diags
}
if postServer.Id != nil {
d.SetId(*postServer.Id)
}
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutCreate); errState != nil {
if cloudapi.IsRequestFailed(errState) {
log.Printf("[DEBUG] failed to create server resource")
d.SetId("")
}
return diag.FromErr(fmt.Errorf("error waiting for state change for server creation %w", errState))
}
// Logic for labels creation
ls := LabelsService{ctx: ctx, client: client}
if err := ls.datacentersServersLabelsCreate(datacenterId, *postServer.Id, d.Get("label")); err != nil {
return diag.FromErr(err)
}
// get additional data for schema
foundServer, apiResponse, err := client.ServersApi.DatacentersServersFindById(ctx, datacenterId, *postServer.Id).Depth(4).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("error fetching server: %w", err))
return diags
}
if foundServer.Entities.Nics.Items != nil {
if len(*foundServer.Entities.Nics.Items) > 0 {
// what we get from backend
foundFirstNic := (*foundServer.Entities.Nics.Items)[0]
var orderedRuleIds []string
if foundFirstNic.Entities != nil && foundFirstNic.Entities.Firewallrules != nil && foundFirstNic.Entities.Firewallrules.Items != nil {
// what we get from schema and send to the API
sentFirstNic := (*serverReq.Entities.Nics.Items)[0]
if sentFirstNic.Entities != nil && sentFirstNic.Entities.Firewallrules != nil && sentFirstNic.Entities.Firewallrules.Items != nil {
sentRules := *sentFirstNic.Entities.Firewallrules.Items
foundRules := *foundFirstNic.Entities.Firewallrules.Items
orderedRuleIds = cloudapifirewall.ExtractOrderedFirewallIds(foundRules, sentRules)
if len(orderedRuleIds) > 0 {
if err := d.Set("firewallrule_id", orderedRuleIds[0]); err != nil {
diags := diag.FromErr(err)
return diags
}
}
}
}
if len(orderedRuleIds) > 0 {
if err := cloudapifirewall.SetIdsInSchema(d, orderedRuleIds); err != nil {
diags := diag.FromErr(err)
return diags
}
}
if foundFirstNic.Id != nil {
err := d.Set("primary_nic", *foundFirstNic.Id)
if err != nil {
diags := diag.FromErr(fmt.Errorf("error while setting primary nic %s: %w", d.Id(), err))
return diags
}
}
foundNicProps := foundFirstNic.Properties
if foundNicProps != nil {
firstNicIps := foundNicProps.Ips
if firstNicIps != nil &&
len(*firstNicIps) > 0 {
log.Printf("[DEBUG] set primary_ip to %s", (*firstNicIps)[0])
if err := d.Set("primary_ip", (*firstNicIps)[0]); err != nil {
diags := diag.FromErr(utils.GenerateSetError("ionoscloud_server", "primary_ip", err))
return diags
}
}
volumeItems := serverReq.Entities.Volumes.Items
firstVolumeItem := (*volumeItems)[0]
if foundNicProps.Ips != nil &&
len(*firstNicIps) > 0 &&
volumeItems != nil &&
len(*volumeItems) > 0 &&
firstVolumeItem.Properties != nil &&
firstVolumeItem.Properties.ImagePassword != nil {
d.SetConnInfo(map[string]string{
"type": "ssh",
"host": (*firstNicIps)[0],
"password": *firstVolumeItem.Properties.ImagePassword,
})
}
}
}
}
// Set inline volumes
if foundServer.Entities.Volumes != nil && foundServer.Entities.Volumes.Items != nil {
var inlineVolumeIds []string
for _, volume := range *foundServer.Entities.Volumes.Items {
inlineVolumeIds = append(inlineVolumeIds, *volume.Id)
}
if err := d.Set("inline_volume_ids", inlineVolumeIds); err != nil {
return diag.FromErr(utils.GenerateSetError("server", "inline_volume_ids", err))
}
}
if initialState, ok := d.GetOk("vm_state"); ok {
ss := cloudapiserver.Service{Client: client, Meta: meta, D: d}
initialState := initialState.(string)
if !strings.EqualFold(initialState, constant.VMStateStart) {
err := ss.Stop(ctx, datacenterId, d.Id(), serverType)
if err != nil {
return diag.FromErr(err)
}
}
}
return resourceServerRead(ctx, d, meta)
}
func resourceServerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
dcId := d.Get("datacenter_id").(string)
serverId := d.Id()
server, apiResponse, err := client.ServersApi.DatacentersServersFindById(ctx, dcId, serverId).Depth(4).Execute()
logApiRequestTime(apiResponse)
if err != nil {
if httpNotFound(apiResponse) {
log.Printf("[DEBUG] cannot find server by id \n")
d.SetId("")
return nil
}
diags := diag.FromErr(fmt.Errorf("error occured while fetching a server ID %s %w", d.Id(), err))
return diags
}
if err := setResourceServerData(ctx, client, d, &server); err != nil {
return diag.FromErr(err)
}
return nil
}
func SetVolumeProperties(volume ionoscloud.Volume) map[string]interface{} {
volumeMap := map[string]interface{}{}
if volume.Properties != nil {
if volume.Properties.SshKeys != nil && len(*volume.Properties.SshKeys) > 0 {
var sshKeys []interface{}
for _, sshKey := range *volume.Properties.SshKeys {
sshKeys = append(sshKeys, sshKey)
}
volumeMap["ssh_keys"] = sshKeys
}
utils.SetPropWithNilCheck(volumeMap, "image_password", volume.Properties.ImagePassword)
utils.SetPropWithNilCheck(volumeMap, "name", volume.Properties.Name)
utils.SetPropWithNilCheck(volumeMap, "size", volume.Properties.Size)
utils.SetPropWithNilCheck(volumeMap, "disk_type", volume.Properties.Type)
utils.SetPropWithNilCheck(volumeMap, "licence_type", volume.Properties.LicenceType)
utils.SetPropWithNilCheck(volumeMap, "bus", volume.Properties.Bus)
utils.SetPropWithNilCheck(volumeMap, "availability_zone", volume.Properties.AvailabilityZone)
utils.SetPropWithNilCheck(volumeMap, "cpu_hot_plug", volume.Properties.CpuHotPlug)
utils.SetPropWithNilCheck(volumeMap, "ram_hot_plug", volume.Properties.RamHotPlug)
utils.SetPropWithNilCheck(volumeMap, "nic_hot_plug", volume.Properties.NicHotPlug)
utils.SetPropWithNilCheck(volumeMap, "nic_hot_unplug", volume.Properties.NicHotUnplug)
utils.SetPropWithNilCheck(volumeMap, "disc_virtio_hot_plug", volume.Properties.DiscVirtioHotPlug)
utils.SetPropWithNilCheck(volumeMap, "disc_virtio_hot_unplug", volume.Properties.DiscVirtioHotUnplug)
utils.SetPropWithNilCheck(volumeMap, "device_number", volume.Properties.DeviceNumber)
utils.SetPropWithNilCheck(volumeMap, "user_data", volume.Properties.UserData)
utils.SetPropWithNilCheck(volumeMap, "backup_unit_id", volume.Properties.BackupunitId)
utils.SetPropWithNilCheck(volumeMap, "boot_server", volume.Properties.BootServer)
}
return volumeMap
}
func resourceServerUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
ss := cloudapiserver.Service{Client: client, Meta: meta, D: d}
dcId := d.Get("datacenter_id").(string)
request := ionoscloud.ServerProperties{}
currentVmState, err := ss.GetVmState(ctx, dcId, d.Id())
if err != nil {
diags := diag.FromErr(fmt.Errorf("could not retrieve server vmState: %w", err))
return diags
}
if strings.EqualFold(currentVmState, constant.CubeVMStateStop) && !d.HasChange("vm_state") {
diags := diag.FromErr(fmt.Errorf("cannot update a suspended Cube Server, must change the state to RUNNING first"))
return diags
}
if d.HasChange("vm_state") {
_, newState := d.GetChange("vm_state")
err := ss.UpdateVmState(ctx, dcId, d.Id(), newState.(string))
if err != nil && !errors.Is(err, cloudapiserver.ErrSuspendCubeLast) {
diags := diag.FromErr(err)
return diags
}
}
if d.HasChange("template_uuid") {
_, n := d.GetChange("template_uuid")
nStr := n.(string)
request.TemplateUuid = &nStr
}
if d.HasChange("name") {
_, n := d.GetChange("name")
nStr := n.(string)
request.Name = &nStr
}
if d.HasChange("cores") {
_, n := d.GetChange("cores")
nInt := int32(n.(int))
request.Cores = &nInt
}
if d.HasChange("ram") {
_, n := d.GetChange("ram")
nInt := int32(n.(int))
request.Ram = &nInt
}
if d.HasChange("type") {
_, n := d.GetChange("type")
nStr := n.(string)
request.Type = &nStr
}
if d.HasChange("cpu_family") {
_, n := d.GetChange("cpu_family")
nStr := n.(string)
request.CpuFamily = &nStr
}
if d.HasChange("boot_cdrom") {
_, n := d.GetChange("boot_cdrom")
bootCdrom := n.(string)
if utils.IsValidUUID(bootCdrom) {
ss := cloudapiserver.Service{Client: meta.(services.SdkBundle).CloudApiClient, Meta: meta, D: d}
ss.UpdateBootDevice(ctx, dcId, d.Id(), bootCdrom)
}
}
server, apiResponse, err := client.ServersApi.DatacentersServersPatch(ctx, dcId, d.Id()).Server(request).Depth(3).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("error occured while updating server ID %s: %w", d.Id(), err))
return diags
}
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutUpdate); errState != nil {
return diag.FromErr(errState)
}
// Volume stuff
if d.HasChange("volume") {
properties := ionoscloud.VolumeProperties{}
inlineVolumeIds := d.Get("inline_volume_ids")
if inlineVolumeIds != nil {
inlineVolumeIds := inlineVolumeIds.([]interface{})
for i, volumeId := range inlineVolumeIds {
volumeIdStr := volumeId.(string)
volumePath := fmt.Sprintf("volume.%d.", i)
_, apiResponse, err := client.ServersApi.DatacentersServersVolumesFindById(ctx, dcId, d.Id(), volumeIdStr).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("an error occured while getting a volume dcId: %s server_id: %s ID: %s Response: %s", dcId, d.Id(), volumeId, err))
return diags
}
if v, ok := d.GetOk(volumePath + "name"); ok {
vStr := v.(string)
properties.Name = &vStr
}
if v, ok := d.GetOk(volumePath + "size"); ok {
vInt := float32(v.(int))
properties.Size = &vInt
}
if v, ok := d.GetOk(volumePath + "bus"); ok {
vStr := v.(string)
properties.Bus = &vStr
}
_, apiResponse, err = client.VolumesApi.DatacentersVolumesPatch(ctx, d.Get("datacenter_id").(string), volumeIdStr).Volume(properties).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("error patching volume (%s) (%w)", d.Id(), err))
return diags
}
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutUpdate); errState != nil {
return diag.FromErr(errState)
}
}
}
}
// Nic stuff
if d.HasChange("nic") {
oldNics, newNics := d.GetChange("nic")
ns := cloudapinic.Service{Client: client, Meta: meta, D: d}
var deleteNic = false
var createNic = false
if (len(oldNics.([]any)) > 0) && (len(newNics.([]any)) == 0) {
deleteNic = true
}
if (len(newNics.([]any)) > 0) && (len(oldNics.([]any)) == 0) {
createNic = true
}
if deleteNic {
apiResponse, err = ns.Delete(ctx, d.Get("datacenter_id").(string), *server.Id, d.Get("primary_nic").(string))
if err != nil {
diags := diag.FromErr(fmt.Errorf("error deleting nic (%w)", err))
return diags
}
err = d.Set("nic", nil)
if err := d.Set("primary_nic", ""); err != nil {
diags := diag.FromErr(err)
return diags
}
if err := d.Set("primary_ip", ""); err != nil {
diags := diag.FromErr(err)
return diags
}
} else {
primaryNic := d.Get("primary_nic").(string)
nic := &ionoscloud.Nic{}
for _, n := range *server.Entities.Nics.Items {
if *n.Id == primaryNic {
nic = &n
break
}
}
lan := int32(d.Get("nic.0.lan").(int))
nicProperties := ionoscloud.NicProperties{
Lan: &lan,
}
if v, ok := d.GetOk("nic.0.name"); ok {
vStr := v.(string)
nicProperties.Name = &vStr
}
if v, ok := d.GetOk("nic.0.ipv6_cidr_block"); ok {
ipv6Block := v.(string)
nicProperties.Ipv6CidrBlock = &ipv6Block