/
resource_server.go
627 lines (566 loc) · 17 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
package kamatera
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceServer() *schema.Resource {
return &schema.Resource{
CreateContext: resourceServerCreate,
ReadContext: resourceServerRead,
UpdateContext: resourceServerUpdate,
DeleteContext: resourceServerDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceServerImport,
},
Description: "It's recommended to use our " +
"[server configuration interface]" +
"(https://kamatera.github.io/kamateratoolbox/serverconfiggen.html?configformat=terraform) " +
"which provides ready to use Terraform templates with valid configuration options and identifiers " +
"according to your selection.",
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "The server name.",
},
"datacenter_id": {
Type: schema.TypeString,
Required: true,
Description: "id attribute of datacenter data source.",
},
"cpu_type": {
Type: schema.TypeString,
Optional: true,
Description: "The CPU type - a single upper-case letter. See https://console.kamatera.com/pricing for " +
"available CPU types and description of each type.",
},
"cpu_cores": {
Type: schema.TypeFloat,
Optional: true,
Description: "Number of CPU cores to allocate. See https://console.kamatera.com/pricing for a " +
"a description of the meaning of this value depending on the selected CPU type.",
},
"ram_mb": {
Type: schema.TypeFloat,
Optional: true,
Description: "Amount of RAM to allocate in MB.",
},
"disk_sizes_gb": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeFloat},
MinItems: 1,
MaxItems: 4,
Optional: true,
Description: "List of disk sizes in GB, each item in the list will create a new disk in given " +
"size and attach it to the server.",
},
"billing_cycle": {
Type: schema.TypeString,
Optional: true,
Default: "hourly",
Description: "hourly or monthly, see https://console.kamatera.com/pricing for details.",
},
"monthly_traffic_package": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "For advanced use-cases you can select a specific traffic package, depending on " +
"datacenter availability. See https://console.kamatera.com/pricing for details.",
},
"power_on": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "true by default, set to false to have the server created without powering it on.",
},
"image_id": {
Type: schema.TypeString,
Required: true,
Description: "id attribute of image data source",
},
"network": {
Type: schema.TypeList,
MaxItems: 4,
Description: "Network interfaces to attach to the server. If not specified a single WAN interface with " +
"auto IP will be attached.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "Set to 'wan' to attach a public internet interface with auto-allocated IP. " +
"To use a private network, set to full_name attribute of network data source",
},
"ip": {
Type: schema.TypeString,
Optional: true,
Default: "auto",
Description: "The IP to use, leave unset or set to 'auto' to auto-allocate an IP",
},
},
},
Optional: true,
},
"daily_backup": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Set to true to enable daily backups.",
},
"managed": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Set to true for managed support services.",
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
Description: "The server root password.",
},
"ssh_pubkey": {
Type: schema.TypeString,
Optional: true,
Description: "SSH public key to allow access to the server without a password.",
},
"generated_password": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
Description: "In case password was not provided, an auto-generated password will be used.",
},
"price_monthly_on": {
Type: schema.TypeString,
Computed: true,
Description: "The monthly price if server is turned on for the entire month.",
},
"price_hourly_on": {
Type: schema.TypeString,
Computed: true,
Description: "The hourly price if server is turned on for the entire hour.",
},
"price_hourly_off": {
Type: schema.TypeString,
Computed: true,
Description: "The hourly price if server is turned off for the entire hour.",
},
"attached_networks": {
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"network": {
Type: schema.TypeString,
Computed: true,
},
"ips": {
Type: schema.TypeList,
Elem: schema.TypeString,
Computed: true,
},
},
},
Computed: true,
},
"public_ips": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"private_ips": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"internal_server_id": {
Type: schema.TypeString,
Computed: true,
},
"startup_script": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceServerCreate(ctx context.Context, d *schema.ResourceData, m interface{}) (diags diag.Diagnostics) {
provider := m.(*ProviderConfig)
password := d.Get("password").(string)
if password == "" {
password = "__generate__"
}
dailyBackup := "no"
if d.Get("daily_backup").(bool) {
dailyBackup = "yes"
}
managed := "no"
if d.Get("managed").(bool) {
managed = "yes"
}
var networks []string
for _, network := range d.Get("network").([]interface{}) {
network := network.(map[string]interface{})
networks = append(networks, fmt.Sprintf("name=%s,ip=%s", network["name"].(string), network["ip"].(string)))
}
if len(networks) == 0 {
networks = append(networks, "name=wan,ip=auto")
}
powerOn := "no"
if d.Get("power_on").(bool) {
powerOn = "yes"
}
var diskSizesGB []string
{
diskSizes := d.Get("disk_sizes_gb").([]interface{})
for _, v := range diskSizes {
diskSizesGB = append(diskSizesGB, fmt.Sprintf("size=%v", v))
}
}
body := &createServerPostValues{
Name: d.Get("name").(string),
Password: password,
PasswordValidate: password,
SSHKey: d.Get("ssh_pubkey").(string),
Datacenter: d.Get("datacenter_id").(string),
Image: d.Get("image_id").(string),
CPU: fmt.Sprintf("%v%v", d.Get("cpu_cores"), d.Get("cpu_type")),
RAM: d.Get("ram_mb").(float64),
Disk: strings.Join(diskSizesGB, " "),
DailyBackup: dailyBackup,
Managed: managed,
Network: strings.Join(networks, " "),
Quantity: "1",
BillingCycle: d.Get("billing_cycle").(string),
MonthlyPackage: d.Get("monthly_traffic_package").(string),
PowerOn: powerOn,
ScriptFile: d.Get("startup_script").(string),
}
result, err := request(provider, "POST", "service/server", body)
if err != nil {
return diag.FromErr(err)
}
var commandIDs []interface{}
if password == "__generate__" {
response := result.(map[string]interface{})
d.Set("generated_password", response["password"].(string))
commandIDs = response["commandIds"].([]interface{})
} else {
d.Set("generated_password", "")
commandIDs = result.([]interface{})
}
if len(commandIDs) != 1 {
return diag.Errorf("invalid response from Kamatera API: did not return expected command ID")
}
commandID := commandIDs[0].(string)
command, err := waitCommand(provider, commandID)
if err != nil {
return diag.FromErr(err)
}
createLog, hasCreateLog := command["log"]
if !hasCreateLog {
return diag.Errorf("invalid response from Kamatera API: command is missing creation log")
}
createdServerName := ""
for _, line := range strings.Split(createLog.(string), "\n") {
if strings.HasPrefix(line, "Name: ") {
createdServerName = strings.Replace(line, "Name: ", "", 1)
}
}
if createdServerName == "" {
return diag.Errorf("invalid response from Kamatera API: failed to get created server name")
}
d.SetId(createdServerName)
return resourceServerRead(ctx, d, m)
}
func resourceServerRead(ctx context.Context, d *schema.ResourceData, m interface{}) (diags diag.Diagnostics) {
provider := m.(*ProviderConfig)
var body listServersPostValues
if d.Get("internal_server_id").(string) == "" {
body = listServersPostValues{Name: d.Id()}
} else {
body = listServersPostValues{ID: d.Get("internal_server_id").(string)}
}
result, err := request(provider, "POST", fmt.Sprintf("service/server/info"), body)
if err != nil {
return diag.FromErr(err)
}
servers := result.([]interface{})
if len(servers) != 1 {
return diag.Errorf("failed to find server")
}
server := servers[0].(map[string]interface{})
d.Set("id", server["id"].(string))
d.Set("name", server["name"].(string))
cpu := server["cpu"].(string)
d.Set("cpu_type", cpu[1:2])
{
cpuCores, err := strconv.ParseFloat(cpu[0:1], 16)
if err != nil {
return diag.FromErr(err)
}
d.Set("cpu_cores", cpuCores)
}
{
diskSizes := server["diskSizes"].([]interface{})
var diskSizesString []float64
for _, v := range diskSizes {
diskSizesString = append(diskSizesString, v.(float64))
}
d.Set("disk_sizes_gb", diskSizesString)
}
d.Set("power_on", server["power"].(string) == "on")
d.Set("datacenter_id", server["datacenter"].(string))
d.Set("ram_mb", server["ram"].(float64))
d.Set("daily_backup", server["backup"].(string) == "1")
d.Set("managed", server["managed"].(string) == "1")
d.Set("billing_cycle", server["billing"].(string))
d.Set("monthly_traffic_package", server["traffic"].(string))
d.Set("internal_server_id", server["id"].(string))
d.Set("price_monthly_on", server["priceMonthlyOn"].(string))
d.Set("price_hourly_on", server["priceHourlyOn"].(string))
d.Set("price_hourly_off", server["priceHourlyOff"].(string))
networks := server["networks"].([]interface{})
var publicIPs []string
var privateIPs []string
var attachedNetworks []interface{}
for _, network := range networks {
network := network.(map[string]interface{})
attachedNetworks = append(attachedNetworks, network)
if strings.Index(network["network"].(string), "wan-") == 0 {
for _, ip := range network["ips"].([]interface{}) {
publicIPs = append(publicIPs, ip.(string))
}
} else {
for _, ip := range network["ips"].([]interface{}) {
privateIPs = append(privateIPs, ip.(string))
}
}
}
d.Set("public_ips", publicIPs)
d.Set("private_ips", privateIPs)
d.Set("attached_networks", attachedNetworks)
return
}
func resourceServerUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) (diags diag.Diagnostics) {
newCPU := ""
{
var newCPUType interface{}
{
o, n := d.GetChange("cpu_type")
if d.HasChange("cpu_type") {
newCPUType = n
} else {
newCPUType = o
}
}
var newCPUCores interface{}
{
o, n := d.GetChange("cpu_cores")
if d.HasChange("cpu_cores") {
newCPUCores = n
} else {
newCPUCores = o
}
}
if d.HasChanges("cpu_type", "cpu_cores") {
newCPU = fmt.Sprintf("%v%v", newCPUCores, newCPUType)
}
}
var newRAM float64
if d.HasChange("ram_mb") {
_, n := d.GetChange("ram_mb")
newRAM = n.(float64)
}
if d.HasChange("image_id") && d.Get("image_id").(string) != "" {
// TODO: Implement
return diag.Errorf("changing server image is not supported yet")
}
if d.HasChange("network") && len(d.Get("network").([]interface{})) > 0 {
// TODO: Implement
return diag.Errorf("changing server networks is not supported yet")
}
if d.HasChange("ssh_pubkey") {
// TODO: implement
return diag.Errorf("changing server ssh_pubkey is not supported yet")
}
if d.HasChange("startup_script") {
return diag.Errorf("changing server startup_script is not supported")
}
oldBillingCycle := ""
newBillingCycle := ""
if d.HasChange("billing_cycle") {
o, n := d.GetChange("billing_cycle")
oldBillingCycle = o.(string)
newBillingCycle = n.(string)
}
oldTrafficPackage := ""
newTrafficPackage := ""
if d.HasChange("monthly_traffic_package") {
o, n := d.GetChange("monthly_traffic_package")
oldTrafficPackage = o.(string)
newTrafficPackage = n.(string)
}
if d.HasChange("datacenter_id") {
return diag.Errorf("changing datacenter is not supported yet")
}
newDailyBackup := ""
if d.HasChange("daily_backup") {
newDailyBackup = "no"
if d.Get("daily_backup").(bool) {
newDailyBackup = "yes"
}
}
newManaged := ""
if d.HasChange("managed") {
newManaged = "no"
if d.Get("managed").(bool) {
newManaged = "yes"
}
}
provider := m.(*ProviderConfig)
if err := serverConfigure(
provider,
d.Get("internal_server_id").(string),
newCPU,
newRAM,
oldTrafficPackage, newTrafficPackage,
oldBillingCycle, newBillingCycle,
newDailyBackup,
newManaged,
); err != nil {
return diag.FromErr(err)
}
if d.HasChange("disk_sizes_gb") {
o, n := d.GetChange("disk_sizes_gb")
op, err := calDiskChangeOperation(o, n)
if err != nil {
return diag.FromErr(err)
}
err = changeDisks(provider, d.Get("internal_server_id").(string), op)
if err != nil {
return diag.FromErr(err)
}
}
if d.HasChange("password") {
o, n := d.GetChange("password")
err := serverChangePassword(provider, d.Get("internal_server_id").(string), n.(string))
if err != nil {
d.Set("password", o)
return diag.FromErr(err)
}
d.Set("password", n)
}
if d.HasChange("name") {
_, n := d.GetChange("name")
if err := renameServer(provider, d.Get("internal_server_id").(string), n.(string)); err != nil {
return diag.FromErr(err)
}
d.Set("name", n)
}
if d.HasChange("power_on") {
if d.Get("power_on").(bool) {
if err := changeServerPower(provider, d.Get("internal_server_id").(string), "poweron"); err != nil {
return diag.FromErr(err)
}
} else {
if err := changeServerPower(provider, d.Get("internal_server_id").(string), "poweroff"); err != nil {
return diag.FromErr(err)
}
}
}
return resourceServerRead(ctx, d, m)
}
func resourceServerDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
provider := m.(*ProviderConfig)
err := changeServerPower(provider, d.Get("internal_server_id").(string), "terminate")
if err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceServerImport(ctx context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
d.Set("internal_server_id", d.Id())
diags := resourceServerRead(ctx, d, m)
if diags.HasError() {
var errorMessages []string
for i := range diags {
errorMessages = append(errorMessages, diags[i].Summary)
}
return nil, fmt.Errorf(strings.Join(errorMessages, ", "))
}
return []*schema.ResourceData{d}, nil
}
func serverConfigure(
provider *ProviderConfig, internalServerId string, newCpu string, newRam float64,
oldTrafficPackage string, newTrafficPackage string, oldBillingCycle string, newBillingCycle string,
newDailyBackup string, newManaged string,
) error {
if newCpu != "" {
if e := postServerConfigure(
provider,
configureServerPostValues{ID: internalServerId, CPU: newCpu},
); e != nil {
return e
}
}
if newRam != 0 {
if e := postServerConfigure(
provider,
configureServerPostValues{ID: internalServerId, RAM: newRam},
); e != nil {
return e
}
}
if newTrafficPackage != "" || newBillingCycle != "" {
billingCycle := ""
if newBillingCycle != "" {
billingCycle = newBillingCycle
}
trafficPackage := oldTrafficPackage
if newTrafficPackage != "" {
trafficPackage = newTrafficPackage
}
if e := postServerConfigure(
provider,
configureServerPostValues{ID: internalServerId, MonthlyPackage: trafficPackage, BillingCycle: billingCycle},
); e != nil {
return e
}
}
if newDailyBackup != "" {
if e := postServerConfigure(
provider,
configureServerPostValues{ID: internalServerId, DailyBackup: newDailyBackup},
); e != nil {
return e
}
}
if newManaged != "" {
if e := postServerConfigure(
provider,
configureServerPostValues{ID: internalServerId, Managed: newManaged},
); e != nil {
return e
}
}
return nil
}
func changeServerPower(provider *ProviderConfig, internalServerID string, operation string) error {
var body powerOperationServerPostValues
if operation == "terminate" {
body = powerOperationServerPostValues{ID: internalServerID, Force: true}
} else {
body = powerOperationServerPostValues{ID: internalServerID}
}
result, err := request(provider, "POST", fmt.Sprintf("service/server/%s", operation), body)
if err != nil {
return err
}
commandIds := result.([]interface{})
_, err = waitCommand(provider, commandIds[0].(string))
return err
}