forked from sacloud/terraform-provider-sakuracloud
/
resource_sakuracloud_disk.go
449 lines (389 loc) · 11.3 KB
/
resource_sakuracloud_disk.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
package sakuracloud
import (
"fmt"
"github.com/docker/go-units"
"github.com/hashicorp/terraform/helper/schema"
"github.com/sacloud/libsacloud/api"
"github.com/sacloud/libsacloud/sacloud"
"log"
"time"
)
func resourceSakuraCloudDisk() *schema.Resource {
return &schema.Resource{
Create: resourceSakuraCloudDiskCreate,
Read: resourceSakuraCloudDiskRead,
Update: resourceSakuraCloudDiskUpdate,
Delete: resourceSakuraCloudDiskDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"plan": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "ssd",
ValidateFunc: validateStringInWord([]string{"ssd", "hdd"}),
},
"connection": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: sacloud.DiskConnectionVirtio,
ValidateFunc: validateStringInWord([]string{
fmt.Sprintf("%s", sacloud.DiskConnectionVirtio),
fmt.Sprintf("%s", sacloud.DiskConnectionIDE),
}),
},
"source_archive_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
ConflictsWith: []string{"source_disk_id"},
ValidateFunc: validateSakuracloudIDType,
},
"source_disk_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
ConflictsWith: []string{"source_archive_id"},
ValidateFunc: validateSakuracloudIDType,
},
"size": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 20,
},
"server_id": {
Type: schema.TypeString,
Computed: true, //ReadOnly
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"tags": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"zone": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: "target SakuraCloud zone",
ValidateFunc: validateStringInWord([]string{"is1a", "is1b", "tk1a", "tk1v"}),
},
"hostname": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(1, 64),
},
"password": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(8, 64),
Sensitive: true,
},
"ssh_key_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
// ! Current terraform(v0.7) is not support to array validation !
// ValidateFunc: validateSakuracloudIDArrayType,
},
"disable_pw_auth": {
Type: schema.TypeBool,
Optional: true,
},
"note_ids": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
// ! Current terraform(v0.7) is not support to array validation !
// ValidateFunc: validateSakuracloudIDArrayType,
},
},
}
}
func resourceSakuraCloudDiskCreate(d *schema.ResourceData, meta interface{}) error {
c := meta.(*api.Client)
client := c.Clone()
zone, ok := d.GetOk("zone")
if ok {
client.Zone = zone.(string)
}
opts := client.Disk.New()
opts.Name = d.Get("name").(string)
plan := d.Get("plan").(string)
switch plan {
case "ssd":
opts.SetDiskPlanToSSD()
break
case "hdd":
opts.SetDiskPlanToHDD()
break
default:
return fmt.Errorf("invalid disk plan [%s]", plan)
}
opts.Connection = sacloud.EDiskConnection(d.Get("connection").(string))
archiveID, ok := d.GetOk("source_archive_id")
if ok {
opts.SetSourceArchive(toSakuraCloudID(archiveID.(string)))
}
diskID, ok := d.GetOk("source_disk_id")
if ok {
opts.SetSourceDisk(toSakuraCloudID(diskID.(string)))
}
opts.SizeMB = d.Get("size").(int) * units.GiB / units.MiB
if description, ok := d.GetOk("description"); ok {
opts.Description = description.(string)
}
rawTags := d.Get("tags").([]interface{})
if rawTags != nil {
opts.Tags = expandStringList(rawTags)
}
disk, err := client.Disk.Create(opts)
if err != nil {
return fmt.Errorf("Failed to create SakuraCloud Disk resource: %s", err)
}
err = client.Disk.SleepWhileCopying(disk.ID, client.DefaultTimeoutDuration)
if err != nil {
return fmt.Errorf("Failed to create SakuraCloud Disk resource: %s", err)
}
//edit disk
diskEditConfig := client.Disk.NewCondig()
if hostName, ok := d.GetOk("hostname"); ok {
diskEditConfig.SetHostName(hostName.(string))
}
if password, ok := d.GetOk("password"); ok {
diskEditConfig.SetPassword(password.(string))
}
if sshKeyIDs, ok := d.GetOk("ssh_key_ids"); ok {
ids := expandStringList(sshKeyIDs.([]interface{}))
diskEditConfig.SetSSHKeys(ids)
}
if disablePasswordAuth, ok := d.GetOk("disable_pw_auth"); ok {
diskEditConfig.SetDisablePWAuth(disablePasswordAuth.(bool))
}
if noteIDs, ok := d.GetOk("note_ids"); ok {
ids := expandStringList(noteIDs.([]interface{}))
diskEditConfig.SetNotes(ids)
}
// call disk edit API
res, err := client.Disk.CanEditDisk(disk.ID)
if err != nil {
return fmt.Errorf("Failed to check CanEditDisk: %s", err)
}
if res {
_, err = client.Disk.Config(disk.ID, diskEditConfig)
if err != nil {
return fmt.Errorf("Error editting SakuraCloud DiskConfig: %s", err)
}
} else {
log.Printf("[WARN] Disk[%d] does not support modify disk", disk.ID)
}
server_id, ok := d.GetOk("server_id")
if ok {
_, err = client.Disk.ConnectToServer(disk.ID, toSakuraCloudID(server_id.(string)))
if err != nil {
return fmt.Errorf("Failed to connect SakuraCloud Disk resource: %s", err)
}
}
d.SetId(disk.GetStrID())
return resourceSakuraCloudDiskRead(d, meta)
}
func resourceSakuraCloudDiskRead(d *schema.ResourceData, meta interface{}) error {
c := meta.(*api.Client)
client := c.Clone()
zone, ok := d.GetOk("zone")
if ok {
client.Zone = zone.(string)
}
disk, err := client.Disk.Read(toSakuraCloudID(d.Id()))
if err != nil {
return fmt.Errorf("Couldn't find SakuraCloud Disk resource: %s", err)
}
return setDiskResourceData(d, client, disk)
}
func resourceSakuraCloudDiskUpdate(d *schema.ResourceData, meta interface{}) error {
c := meta.(*api.Client)
client := c.Clone()
zone, ok := d.GetOk("zone")
if ok {
client.Zone = zone.(string)
}
disk, err := client.Disk.Read(toSakuraCloudID(d.Id()))
if err != nil {
return fmt.Errorf("Couldn't find SakuraCloud Disk resource: %s", err)
}
// has server_id and server is up,shutdown
isRunning := disk.Server != nil && disk.Server.Instance.IsUp()
isDiskConfigChanged := false
if d.HasChange("hostname") || d.HasChange("password") || d.HasChange("ssh_key_ids") || d.HasChange("disable_pw_auth") || d.HasChange("note_ids") {
isDiskConfigChanged = true
}
if isRunning && isDiskConfigChanged {
_, err := client.Server.Shutdown(disk.Server.ID)
if err != nil {
return fmt.Errorf("Error stopping SakuraCloud Server resource: %s", err)
}
err = client.Server.SleepUntilDown(disk.Server.ID, client.DefaultTimeoutDuration)
if err != nil {
return fmt.Errorf("Error stopping SakuraCloud Server resource: %s", err)
}
}
if isDiskConfigChanged {
diskEditConfig := client.Disk.NewCondig()
if d.HasChange("hostname") {
if hostName, ok := d.GetOk("hostname"); ok {
diskEditConfig.SetHostName(hostName.(string))
} else {
diskEditConfig.HostName = nil
}
}
if d.HasChange("password") {
if password, ok := d.GetOk("password"); ok {
diskEditConfig.SetPassword(password.(string))
} else {
diskEditConfig.SetPassword("")
}
}
if d.HasChange("ssh_key_ids") {
if sshKeyIDs, ok := d.GetOk("ssh_key_ids"); ok {
ids := expandStringList(sshKeyIDs.([]interface{}))
diskEditConfig.SetSSHKeys(ids)
} else {
diskEditConfig.SSHKeys = nil
}
}
if d.HasChange("disable_pw_auth") {
diskEditConfig.SetDisablePWAuth(d.Get("disable_pw_auth").(bool))
}
if d.HasChange("note_ids") {
if noteIDs, ok := d.GetOk("note_ids"); ok {
ids := expandStringList(noteIDs.([]interface{}))
diskEditConfig.SetNotes(ids)
} else {
diskEditConfig.Notes = nil
}
}
res, err := client.Disk.CanEditDisk(disk.ID)
if err != nil {
return fmt.Errorf("Failed to check CanEditDisk: %s", err)
}
if res {
_, err := client.Disk.Config(disk.ID, diskEditConfig)
if err != nil {
return fmt.Errorf("Error editting SakuraCloud DiskConfig: %s", err)
}
} else {
log.Printf("[WARN] Disk[%d] does not support modify disk", disk.ID)
}
}
if d.HasChange("name") {
disk.Name = d.Get("name").(string)
}
if d.HasChange("description") {
if description, ok := d.GetOk("description"); ok {
disk.Description = description.(string)
} else {
disk.Description = ""
}
}
if d.HasChange("tags") {
rawTags := d.Get("tags").([]interface{})
if rawTags != nil {
disk.Tags = expandStringList(rawTags)
}
}
disk, err = client.Disk.Update(disk.ID, disk)
if err != nil {
return fmt.Errorf("Error updating SakuraCloud Disk resource: %s", err)
}
d.SetId(disk.GetStrID())
if isRunning && isDiskConfigChanged {
_, err := client.Server.Boot(disk.Server.ID)
if err != nil {
return fmt.Errorf("Error booting SakuraCloud Server resource: %s", err)
}
err = client.Server.SleepUntilUp(disk.Server.ID, client.DefaultTimeoutDuration)
if err != nil {
return fmt.Errorf("Error booting SakuraCloud Server resource: %s", err)
}
}
return resourceSakuraCloudDiskRead(d, meta)
}
func resourceSakuraCloudDiskDelete(d *schema.ResourceData, meta interface{}) error {
c := meta.(*api.Client)
client := c.Clone()
zone, ok := d.GetOk("zone")
if ok {
client.Zone = zone.(string)
}
disk, err := client.Disk.Read(toSakuraCloudID(d.Id()))
if err != nil {
return fmt.Errorf("Couldn't find SakuraCloud Disk resource: %s", err)
}
isRunning := false
if disk.Server != nil {
if disk.Server.Instance.IsUp() {
isRunning = true
time.Sleep(2 * time.Second)
_, err := client.Server.Stop(disk.Server.ID)
if err != nil {
return fmt.Errorf("Error stopping Server: %s", err)
}
err = client.Server.SleepUntilDown(disk.Server.ID, client.DefaultTimeoutDuration)
if err != nil {
return fmt.Errorf("Error stopping Server: %s", err)
}
}
_, err := client.Disk.DisconnectFromServer(toSakuraCloudID(d.Id()))
if err != nil {
return fmt.Errorf("Error disconnecting Disk from SakuraCloud Server: %s", err)
}
}
_, err = client.Disk.Delete(toSakuraCloudID(d.Id()))
if err != nil {
return fmt.Errorf("Error deleting SakuraCloud Disk resource: %s", err)
}
if isRunning {
_, err := client.Server.Boot(disk.Server.ID)
if err != nil {
return fmt.Errorf("Error booting Server: %s", err)
}
err = client.Server.SleepUntilUp(disk.Server.ID, client.DefaultTimeoutDuration)
if err != nil {
return fmt.Errorf("Error booting Server: %s", err)
}
}
return nil
}
func setDiskResourceData(d *schema.ResourceData, client *api.Client, data *sacloud.Disk) error {
d.Set("name", data.Name)
switch data.Plan.ID {
case sacloud.DiskPlanSSD.ID:
d.Set("plan", "ssd")
break
case sacloud.DiskPlanHDD.ID:
d.Set("plan", "hdd")
break
}
d.Set("connection", fmt.Sprintf("%s", data.Connection))
d.Set("size", data.SizeMB*units.MiB/units.GiB)
d.Set("description", data.Description)
d.Set("tags", data.Tags)
if data.Server != nil {
d.Set("server_id", data.Server.GetStrID())
}
d.Set("zone", client.Zone)
d.SetId(data.GetStrID())
return nil
}