forked from cab105/terraform-provider-exoscale
/
resource_compute.go
1033 lines (885 loc) · 24.8 KB
/
resource_compute.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 exoscale
import (
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"github.com/exoscale/egoscale"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)
func computeResource() *schema.Resource {
s := map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"template": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"size": {
Type: schema.TypeString,
Optional: true,
Default: "Medium",
},
"disk_size": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntAtLeast(10),
},
"zone": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"user_data": {
Type: schema.TypeString,
Optional: true,
Description: "cloud-init configuration",
},
"key_pair": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"keyboard": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"de", "de-ch", "es", "fi", "fr", "fr-be", "fr-ch", "is",
"it", "jp", "nl-be", "no", "pt", "uk", "us",
}, true),
},
"state": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{
"Running", "Stopped",
}, true),
},
"ip4": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Request an IPv4 address on the default NIC",
},
"ip6": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Request an IPv6 address on the default NIC",
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"gateway": {
Type: schema.TypeString,
Computed: true,
},
"ip6_address": {
Type: schema.TypeString,
Computed: true,
},
"ip6_cidr": {
Type: schema.TypeString,
Computed: true,
},
"affinity_group_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Set: schema.HashString,
ConflictsWith: []string{"affinity_groups"},
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"affinity_groups": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Set: schema.HashString,
ConflictsWith: []string{"affinity_group_ids"},
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"security_group_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Set: schema.HashString,
ConflictsWith: []string{"security_groups"},
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"security_groups": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Set: schema.HashString,
ConflictsWith: []string{"security_group_ids"},
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"username": {
Type: schema.TypeString,
Computed: true,
},
"password": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
}
addTags(s, "tags")
return &schema.Resource{
Create: createCompute,
Exists: existsCompute,
Read: readCompute,
Update: updateCompute,
Delete: deleteCompute,
Importer: &schema.ResourceImporter{
State: importCompute,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(defaultTimeout),
Read: schema.DefaultTimeout(defaultTimeout),
Update: schema.DefaultTimeout(defaultTimeout),
Delete: schema.DefaultTimeout(defaultTimeout),
},
Schema: s,
}
}
func createCompute(d *schema.ResourceData, meta interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout(schema.TimeoutCreate))
defer cancel()
client := GetComputeClient(meta)
displayName := d.Get("display_name").(string)
hostName := regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9\\-]+$")
if !hostName.MatchString(displayName) {
return fmt.Errorf("At creation time, the `display_name` must match a value compatible with the `hostname` (alpha-numeric and hyphens")
}
// ServiceOffering
size := d.Get("size").(string)
resp, err := client.RequestWithContext(ctx, &egoscale.ListServiceOfferings{
Name: size,
})
if err != nil {
return err
}
services := resp.(*egoscale.ListServiceOfferingsResponse)
if len(services.ServiceOffering) != 1 {
return fmt.Errorf("Unable to find the size: %#v", size)
}
service := services.ServiceOffering[0].ID
// XXX Use Generic Get...
zoneName := d.Get("zone").(string)
zone, err := getZoneByName(ctx, client, zoneName)
if err != nil {
return err
}
diskSize := int64(d.Get("disk_size").(int))
resp, err = client.RequestWithContext(ctx, &egoscale.ListTemplates{
TemplateFilter: "featured",
ZoneID: zone.ID,
})
if err != nil {
return err
}
var templateID *egoscale.UUID
username := ""
currentDiskSize := diskSize << 30 // Gib to B
image := strings.ToLower(d.Get("template").(string))
for _, template := range resp.(*egoscale.ListTemplatesResponse).Template {
// Skip non-machine images
if strings.ToLower(template.Name) != image {
continue
}
if name, ok := template.Details["username"]; username == "" && ok {
username = name
}
if template.Size == diskSize<<30 {
templateID = template.ID
break
}
// Pick the smallest disk size
if template.Size < currentDiskSize {
currentDiskSize = template.Size
templateID = template.ID
continue
}
}
if templateID == nil {
return fmt.Errorf("Template not found: %s (%dGB Disk)", d.Get("template").(string), d.Get("disk_size").(int))
}
if username == "" {
log.Printf("[INFO] Username not found in the template details, falling back to root.")
username = "root"
}
// Affinity Groups
var affinityGroups []string
if affinitySet, ok := d.Get("affinity_groups").(*schema.Set); ok {
affinityGroups = make([]string, affinitySet.Len())
for i, group := range affinitySet.List() {
affinityGroups[i] = group.(string)
}
}
var affinityGroupIDs []egoscale.UUID
if affinityIDSet, ok := d.Get("affinity_group_ids").(*schema.Set); ok {
affinityGroupIDs = make([]egoscale.UUID, affinityIDSet.Len())
for i, group := range affinityIDSet.List() {
id, err := egoscale.ParseUUID(group.(string))
if err != nil {
return err
}
affinityGroupIDs[i] = *id
}
}
// Security Groups
var securityGroups []string
if securitySet, ok := d.Get("security_groups").(*schema.Set); ok {
securityGroups = make([]string, securitySet.Len())
for i, group := range securitySet.List() {
securityGroups[i] = group.(string)
}
}
var securityGroupIDs []egoscale.UUID
if securityIDSet, ok := d.Get("security_group_ids").(*schema.Set); ok {
securityGroupIDs = make([]egoscale.UUID, securityIDSet.Len())
for i, group := range securityIDSet.List() {
id, err := egoscale.ParseUUID(group.(string))
if err != nil {
return err
}
securityGroupIDs[i] = *id
}
}
userData, err := prepareUserData(d, meta, "user_data")
if err != nil {
return err
}
startVM := d.Get("state").(string) != "Stopped"
details := make(map[string]string)
details["ip4"] = strconv.FormatBool(d.Get("ip4").(bool))
details["ip6"] = strconv.FormatBool(d.Get("ip6").(bool))
req := &egoscale.DeployVirtualMachine{
Name: displayName,
DisplayName: displayName,
RootDiskSize: int64(diskSize),
KeyPair: d.Get("key_pair").(string),
Keyboard: d.Get("keyboard").(string),
UserData: userData,
ServiceOfferingID: service,
TemplateID: templateID,
ZoneID: zone.ID,
AffinityGroupIDs: affinityGroupIDs,
AffinityGroupNames: affinityGroups,
SecurityGroupIDs: securityGroupIDs,
SecurityGroupNames: securityGroups,
Details: details,
StartVM: &startVM,
}
resp, err = client.RequestWithContext(ctx, req)
if err != nil {
return err
}
/* Copy VM to our struct */
machine := resp.(*egoscale.VirtualMachine)
d.SetId(machine.ID.String())
cmd, err := createTags(d, "tags", machine.ResourceType())
if err != nil {
return err
}
if cmd != nil {
if err := client.BooleanRequestWithContext(ctx, cmd); err != nil {
// Attempting to destroy the freshly created machine
if e := client.DeleteWithContext(ctx, machine); e != nil {
log.Printf("[WARNING] Failure to create the tags, but the machine was deployed. %v", e)
}
return err
}
}
// Connection info
password := ""
if machine.PasswordEnabled {
password = machine.Password
}
d.Set("username", username)
d.Set("password", password)
return readCompute(d, meta)
}
func existsCompute(d *schema.ResourceData, meta interface{}) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout(schema.TimeoutRead))
defer cancel()
client := GetComputeClient(meta)
id, err := egoscale.ParseUUID(d.Id())
if err != nil {
return false, err
}
machine := &egoscale.VirtualMachine{ID: id}
// The CS API returns an error if it doesn't exist
if err := client.GetWithContext(ctx, machine); err != nil {
e := handleNotFound(d, err)
return d.Id() != "", e
}
return true, nil
}
func readCompute(d *schema.ResourceData, meta interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout(schema.TimeoutRead))
defer cancel()
client := GetComputeClient(meta)
id, err := egoscale.ParseUUID(d.Id())
if err != nil {
return err
}
machine := &egoscale.VirtualMachine{ID: id}
if err := client.GetWithContext(ctx, machine); err != nil {
return handleNotFound(d, err)
}
// user_data
resp, err := client.RequestWithContext(ctx, &egoscale.GetVirtualMachineUserData{
VirtualMachineID: id,
})
if err != nil {
return err
}
userData, err := resp.(*egoscale.VirtualMachineUserData).Decode()
if err != nil {
return err
}
d.Set("user_data", string(userData))
// disk_size
volumes, err := client.ListWithContext(ctx, &egoscale.Volume{
VirtualMachineID: id,
Type: "ROOT",
})
if err != nil {
return err
}
if len(volumes) != 1 {
return fmt.Errorf("ROOT volume not found for the VM %s", d.Id())
}
volume := volumes[0].(*egoscale.Volume)
d.Set("disk_size", volume.Size>>30) // B to GiB
// connection info
username := d.Get("username").(string)
if username == "" {
username = getSSHUsername(machine.TemplateName)
d.Set("username", username)
}
password := d.Get("password").(string)
if machine.PasswordEnabled && password == "" {
resp, err := client.RequestWithContext(ctx, &egoscale.GetVMPassword{
ID: machine.ID,
})
if err != nil {
if r, ok := err.(*egoscale.ErrorResponse); ok {
if r.ErrorCode != egoscale.ParamError && r.ErrorCode != 4350 {
return err
}
} else {
return err
}
} else {
pwd := resp.(*egoscale.Password)
// XXX https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=34014652
password = fmt.Sprintf("base64:%s", pwd.EncryptedPassword)
d.Set("password", password)
}
}
return applyCompute(d, machine)
}
func updateCompute(d *schema.ResourceData, meta interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout(schema.TimeoutUpdate))
defer cancel()
client := GetComputeClient(meta)
id, err := egoscale.ParseUUID(d.Id())
if err != nil {
return err
}
// Get() gives us the new state
initialState := d.Get("state").(string)
if d.HasChange("state") {
o, _ := d.GetChange("state")
initialState = o.(string)
}
if initialState != "Running" && initialState != "Stopped" {
return fmt.Errorf("VM %s must be either Running or Stopped. got %s", d.Id(), initialState)
}
rebootRequired := false
startRequired := false
stopRequired := false
d.Partial(true)
// partialCommand represents an update command, it's made of
// the partial key which is expected to change and the
// request that has to be run.
type partialCommand struct {
partial string
partials []string
request egoscale.Command
}
commands := make([]partialCommand, 0)
// Update command is synchronous, hence it won't be put with the others
req := &egoscale.UpdateVirtualMachine{
ID: id,
}
if d.HasChange("display_name") {
req.DisplayName = d.Get("display_name").(string)
}
if d.HasChange("user_data") {
userData, err := prepareUserData(d, meta, "user_data")
if err != nil {
return err
}
req.UserData = userData
rebootRequired = true
}
if d.HasChange("security_groups") {
rebootRequired = true
securityGroupIDs := make([]egoscale.UUID, 0)
if securitySet, ok := d.Get("security_groups").(*schema.Set); ok {
for _, group := range securitySet.List() {
sg, err := getSecurityGroup(ctx, client, group.(string))
if err != nil {
return err
}
securityGroupIDs = append(securityGroupIDs, *sg.ID)
}
}
if len(securityGroupIDs) == 0 {
return fmt.Errorf("A VM must have at least one Security Group, none found")
}
req.SecurityGroupIDs = securityGroupIDs
} else if d.HasChange("security_group_ids") {
rebootRequired = true
securityGroupIDs := make([]egoscale.UUID, 0)
if securitySet, ok := d.Get("security_group_ids").(*schema.Set); ok {
for _, group := range securitySet.List() {
id, err := egoscale.ParseUUID(group.(string))
if err != nil {
return err
}
securityGroupIDs = append(securityGroupIDs, *id)
}
}
if len(securityGroupIDs) == 0 {
return fmt.Errorf("A VM must have at least one Security Group, none found")
}
req.SecurityGroupIDs = securityGroupIDs
}
if d.HasChange("disk_size") {
o, n := d.GetChange("disk_size")
oldSize := o.(int)
newSize := n.(int)
if oldSize > newSize {
return fmt.Errorf("A volume can only be expanded. From %dG to %dG is not allowed", oldSize, newSize)
}
rebootRequired = true
volumes, err := client.ListWithContext(ctx, &egoscale.Volume{
VirtualMachineID: id,
Type: "ROOT",
})
if err != nil {
return err
}
if len(volumes) != 1 {
return fmt.Errorf("ROOT volume not found for the VM %s", d.Id())
}
volume := volumes[0].(*egoscale.Volume)
commands = append(commands, partialCommand{
partial: "disk_size",
request: &egoscale.ResizeVolume{
ID: volume.ID,
Size: int64(d.Get("disk_size").(int)),
},
})
}
if d.HasChange("size") {
o, n := d.GetChange("size")
oldSize := o.(string)
newSize := n.(string)
if strings.ToLower(oldSize) != strings.ToLower(newSize) {
rebootRequired = true
resp, err := client.RequestWithContext(ctx, &egoscale.ListServiceOfferings{
Name: newSize,
})
if err != nil {
return err
}
services, ok := resp.(*egoscale.ListServiceOfferingsResponse)
if !ok {
return fmt.Errorf("wrong type, a ListServiceOfferingsResponse was expected, got %T", resp)
}
if len(services.ServiceOffering) != 1 {
return fmt.Errorf("size %q was not found", newSize)
}
commands = append(commands, partialCommand{
partial: "size",
request: &egoscale.ScaleVirtualMachine{
ID: id,
ServiceOfferingID: services.ServiceOffering[0].ID,
},
})
}
}
if d.HasChange("affinity_groups") {
rebootRequired = true
o, n := d.GetChange("affinity_groups")
if o.(*schema.Set).Len() >= n.(*schema.Set).Len() {
return fmt.Errorf("Affinity Groups cannot be added.")
}
if n.(*schema.Set).Difference(o.(*schema.Set)).Len() > 0 {
return fmt.Errorf("No new Affinity Groups can be added.")
}
if affinitySet, ok := d.Get("affinity_groups").(*schema.Set); ok {
affinityGroups := make([]string, affinitySet.Len())
for i, group := range affinitySet.List() {
affinityGroups[i] = group.(string)
}
commands = append(commands, partialCommand{
partials: []string{"affinity_groups", "affinity_group_ids"},
request: &egoscale.UpdateVMAffinityGroup{
ID: id,
AffinityGroupNames: affinityGroups,
},
})
}
} else if d.HasChange("affinity_group_ids") {
rebootRequired = true
o, n := d.GetChange("affinity_group_ids")
if o.(*schema.Set).Len() >= n.(*schema.Set).Len() {
return fmt.Errorf("Affinity Groups cannot be added.")
}
if n.(*schema.Set).Difference(o.(*schema.Set)).Len() > 0 {
return fmt.Errorf("No new Affinity Groups can be added.")
}
if affinitySet, ok := d.Get("affinity_group_ids").(*schema.Set); ok {
affinityGroups := make([]egoscale.UUID, affinitySet.Len())
for i, group := range affinitySet.List() {
id, err := egoscale.ParseUUID(group.(string))
if err != nil {
return err
}
affinityGroups[i] = *id
}
commands = append(commands, partialCommand{
partials: []string{"affinity_groups", "affinity_group_ids"},
request: &egoscale.UpdateVMAffinityGroup{
ID: id,
AffinityGroupIDs: affinityGroups,
},
})
}
}
updates, err := updateTags(d, "tags", "userVM")
if err != nil {
return err
}
for _, update := range updates {
commands = append(commands, partialCommand{
partial: "tags",
request: update,
})
}
if d.HasChange("ip4") {
activateIP4 := d.Get("ip4").(bool)
if !activateIP4 {
return fmt.Errorf("The IPv4 address cannot be deactivated")
}
}
if d.HasChange("ip6") {
activateIP6 := d.Get("ip6").(bool)
if activateIP6 {
resp, err := client.Request(&egoscale.ListNics{
VirtualMachineID: id,
})
if err != nil {
return err
}
nics := resp.(*egoscale.ListNicsResponse)
if len(nics.Nic) == 0 {
return fmt.Errorf("The VM has no NIC %v", d.Id())
}
commands = append(commands, partialCommand{
partials: []string{"ip6", "ip6_address", "ip6_cidr"},
request: &egoscale.ActivateIP6{
NicID: nics.Nic[0].ID,
},
})
} else {
return fmt.Errorf("The IPv6 address cannot be deactivated")
}
}
if d.HasChange("state") {
switch d.Get("state").(string) {
case "Running":
startRequired = true
case "Stopped":
stopRequired = true
rebootRequired = false
startRequired = false
default:
return fmt.Errorf("The new state cannot applied, %s. Do it manually", d.Get("state").(string))
}
}
// Stop
if initialState != "Stopped" && (rebootRequired || stopRequired) {
resp, err := client.RequestWithContext(ctx, &egoscale.StopVirtualMachine{
ID: id,
})
if err != nil {
return err
}
m := resp.(*egoscale.VirtualMachine)
if err := applyCompute(d, m); err != nil {
return err
}
d.SetPartial("state")
}
// Update, we ignore the result as a full read is require for the user-data/volume
_, err = client.RequestWithContext(ctx, req)
if err != nil {
return err
}
if err := readCompute(d, meta); err != nil {
return err
}
d.SetPartial("user_data")
d.SetPartial("display_name")
d.SetPartial("security_groups")
if (initialState == "Running" && rebootRequired) || startRequired {
commands = append(commands, partialCommand{
partial: "state",
request: &egoscale.StartVirtualMachine{
ID: id,
},
})
}
for _, cmd := range commands {
_, err := client.RequestWithContext(ctx, cmd.request)
if err != nil {
return err
}
d.SetPartial(cmd.partial)
if cmd.partials != nil {
for _, partial := range cmd.partials {
d.SetPartial(partial)
}
}
}
// Update oneself
err = readCompute(d, meta)
d.Partial(false)
return err
}
func deleteCompute(d *schema.ResourceData, meta interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout(schema.TimeoutDelete))
defer cancel()
client := GetComputeClient(meta)
id, err := egoscale.ParseUUID(d.Id())
if err != nil {
return err
}
err = client.DeleteWithContext(ctx, &egoscale.VirtualMachine{
ID: id,
})
if err != nil {
return err
}
d.SetId("")
return nil
}
func importCompute(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout(schema.TimeoutRead))
defer cancel()
client := GetComputeClient(meta)
machine := &egoscale.VirtualMachine{}
id, err := egoscale.ParseUUID(d.Id())
if err != nil {
machine.Name = d.Id()
} else {
machine.ID = id
}
if err := client.GetWithContext(ctx, machine); err != nil {
if e := handleNotFound(d, err); e != nil {
return nil, e
}
if d.Id() == "" {
return nil, fmt.Errorf("Failure to import the compute resource: %s", id)
}
}
defaultNic := machine.DefaultNic()
if defaultNic == nil {
return nil, fmt.Errorf("VM %v has no default NIC", d.Id())
}
secondaryIPs := defaultNic.SecondaryIP
nics := machine.NicsByType("Isolated")
resources := make([]*schema.ResourceData, 0, 1+len(nics)+len(secondaryIPs))
resources = append(resources, d)
if secondaryIPs != nil {
for _, secondaryIP := range secondaryIPs {
resource := secondaryIPResource()
d := resource.Data(nil)
d.SetType("exoscale_secondary_ipaddress")
d.Set("compute_id", id)
secondaryIP.NicID = defaultNic.ID
secondaryIP.NetworkID = defaultNic.NetworkID
if err := applySecondaryIP(d, &secondaryIP); err != nil {
return nil, err
}
resources = append(resources, d)
}
}
for _, nic := range nics {
resource := nicResource()
d := resource.Data(nil)
d.SetType("exoscale_nic")
if err := applyNic(d, nic); err != nil {
return nil, err
}
resources = append(resources, d)
}
return resources, nil
}
func applyCompute(d *schema.ResourceData, machine *egoscale.VirtualMachine) error {
d.Set("name", machine.Name)
d.Set("display_name", machine.DisplayName)
d.Set("key_pair", machine.KeyPair)
d.Set("size", machine.ServiceOfferingName)
d.Set("template", machine.TemplateName)
d.Set("zone", machine.ZoneName)
d.Set("state", machine.State)
d.Set("ip4", false)
d.Set("ip6", false)
d.Set("ip_address", "")
d.Set("gateway", "")
d.Set("ip6_address", "")
d.Set("ip6_cidr", "")
if nic := machine.DefaultNic(); nic != nil {
d.Set("ip4", true)
if nic.IPAddress != nil {
d.Set("ip_address", nic.IPAddress.String())
}
if nic.Gateway != nil {
d.Set("gateway", nic.Gateway.String())
}
if nic.IP6Address != nil {
d.Set("ip6", true)
d.Set("ip6_address", nic.IP6Address.String())
}
if nic.IP6CIDR != nil {
d.Set("ip6_cidr", nic.IP6CIDR.String())
}
}
// affinity groups
affinityGroups := make([]string, len(machine.AffinityGroup))
affinityGroupIDs := make([]egoscale.UUID, len(machine.AffinityGroup))
for i, ag := range machine.AffinityGroup {
affinityGroups[i] = ag.Name
affinityGroupIDs[i] = *ag.ID
}
d.Set("affinity_groups", affinityGroups)
d.Set("affinity_group_ids", affinityGroupIDs)
// security groups
securityGroups := make([]string, len(machine.SecurityGroup))
securityGroupIDs := make([]egoscale.UUID, len(machine.SecurityGroup))
for i, sg := range machine.SecurityGroup {
securityGroups[i] = sg.Name
securityGroupIDs[i] = *sg.ID
}
d.Set("security_groups", securityGroups)
d.Set("security_group_ids", securityGroupIDs)
// tags
tags := make(map[string]interface{})
for _, tag := range machine.Tags {
tags[tag.Key] = tag.Value
}
d.Set("tags", tags)
// Connection info for the provisioners
connInfo := map[string]string{
"type": "ssh",
"user": d.Get("username").(string),
"host": d.Get("ip_address").(string),
}
if d.Get("password").(string) != "" {
connInfo["password"] = d.Get("password").(string)
}
d.SetConnInfo(connInfo)
return nil
}
func getSSHUsername(template string) string {
name := strings.ToLower(template)
if strings.Contains(name, "ubuntu") {
return "ubuntu"
}
if strings.Contains(name, "centos") {
return "centos"
}
if strings.Contains(name, "redhat") {
return "cloud-user"
}
if strings.Contains(name, "fedora") {
return "fedora"
}
if strings.Contains(name, "coreos") {
return "core"
}
if strings.Contains(name, "debian") {
return "debian"
}
return "root"
}
func getSecurityGroup(ctx context.Context, client *egoscale.Client, name string) (*egoscale.SecurityGroup, error) {
sg := &egoscale.SecurityGroup{Name: name}
err := client.GetWithContext(ctx, sg)
if err != nil {
return nil, err
}
return sg, nil
}
// isUuid matches a UUIDv4