-
Notifications
You must be signed in to change notification settings - Fork 1
/
resource_viettelidc_images_image_v2.go
556 lines (464 loc) · 14.3 KB
/
resource_viettelidc_images_image_v2.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
package viettelidc
import (
"context"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/imagedata"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
)
func resourceImagesImageV2() *schema.Resource {
return &schema.Resource{
CreateContext: resourceImagesImageV2Create,
ReadContext: resourceImagesImageV2Read,
UpdateContext: resourceImagesImageV2Update,
DeleteContext: resourceImagesImageV2Delete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
CustomizeDiff: resourceImagesImageV2UpdateComputedAttributes,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"container_format": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"ami", "ari", "aki", "bare", "ovf", "ova",
}, false),
},
"disk_format": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"ami", "ari", "aki", "vhd", "vmdk", "raw", "qcow2", "vdi", "iso",
}, false),
},
"file": {
Type: schema.TypeString,
Computed: true,
},
"image_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.IsUUID,
},
"image_cache_path": {
Type: schema.TypeString,
Optional: true,
Default: fmt.Sprintf("%s/.terraform/image_cache", os.Getenv("HOME")),
},
"image_source_url": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"local_file_path"},
},
"image_source_username": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"local_file_path"},
},
"image_source_password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"local_file_path"},
},
"local_file_path": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"image_source_url", "web_download"},
},
"min_disk_gb": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
Default: 0,
},
"min_ram_mb": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
Default: 0,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: false,
},
"protected": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"hidden": {
Type: schema.TypeBool,
Optional: true,
ForceNew: false,
Default: false,
},
"tags": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"verify_checksum": {
Type: schema.TypeBool,
Optional: true,
ForceNew: false,
ConflictsWith: []string{"web_download"},
},
"visibility": {
Type: schema.TypeString,
Optional: true,
ForceNew: false,
ValidateFunc: validation.StringInSlice([]string{
"public", "private", "shared", "community",
}, false),
Default: "private",
},
"properties": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
},
"web_download": {
Type: schema.TypeBool,
Optional: true,
ForceNew: false,
ConflictsWith: []string{"local_file_path", "verify_checksum", "decompress"},
},
"decompress": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"web_download"},
},
// Computed-only
"checksum": {
Type: schema.TypeString,
Computed: true,
},
"created_at": {
Type: schema.TypeString,
Computed: true,
},
"metadata": {
Type: schema.TypeMap,
Computed: true,
},
"owner": {
Type: schema.TypeString,
Computed: true,
},
"schema": {
Type: schema.TypeString,
Computed: true,
},
"size_bytes": {
Type: schema.TypeInt,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"update_at": {
Type: schema.TypeString,
Computed: true,
Deprecated: "Use updated_at instead",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceImagesImageV2Create(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*Config)
imageClient, err := config.ImageV2Client(GetRegion(d, config))
if err != nil {
return diag.Errorf("Error creating OpenStack image client: %s", err)
}
protected := d.Get("protected").(bool)
visibility := resourceImagesImageV2VisibilityFromString(d.Get("visibility").(string))
properties := d.Get("properties").(map[string]interface{})
imageProperties := resourceImagesImageV2ExpandProperties(properties)
createOpts := &images.CreateOpts{
Name: d.Get("name").(string),
ContainerFormat: d.Get("container_format").(string),
DiskFormat: d.Get("disk_format").(string),
MinDisk: d.Get("min_disk_gb").(int),
MinRAM: d.Get("min_ram_mb").(int),
ID: d.Get("image_id").(string),
Protected: &protected,
Visibility: &visibility,
Properties: imageProperties,
}
if d.Get("hidden").(bool) {
hidden := true
createOpts.Hidden = &hidden
}
if v, ok := d.GetOk("tags"); ok {
tags := v.(*schema.Set).List()
createOpts.Tags = resourceImagesImageV2BuildTags(tags)
}
d.Partial(true)
log.Printf("[DEBUG] Create Options: %#v", createOpts)
newImg, err := images.Create(imageClient, createOpts).Extract()
if err != nil {
return diag.Errorf("Error creating Image: %s", err)
}
d.SetId(newImg.ID)
var fileChecksum string
useWebDownload := d.Get("web_download").(bool)
if useWebDownload {
// import
imgURL := d.Get("image_source_url").(string)
importOpts := &imageimport.CreateOpts{
Name: imageimport.WebDownloadMethod,
URI: imgURL,
}
log.Printf("[DEBUG] Import Options: %#v", importOpts)
err = imageimport.Create(imageClient, d.Id(), importOpts).ExtractErr()
if err != nil {
return diag.Errorf("Error while importing url %q: %s", imgURL, err)
}
} else {
// variable declaration
var err error
var imgFilePath string
var fileSize int64
var imgFile *os.File
// downloading/getting image file props
imgFilePath, err = resourceImagesImageV2File(imageClient, d, config.MutexKV)
if err != nil {
return diag.Errorf("Error opening file for Image: %s", err)
}
fileSize, fileChecksum, err = resourceImagesImageV2FileProps(imgFilePath)
if err != nil {
return diag.Errorf("Error getting file props: %s", err)
}
// upload
imgFile, err = os.Open(imgFilePath)
if err != nil {
return diag.Errorf("Error opening file %q: %s", imgFilePath, err)
}
defer imgFile.Close()
log.Printf("[WARN] Uploading image %s (%d bytes). This can be pretty long.", d.Id(), fileSize)
err = imagedata.Upload(imageClient, d.Id(), imgFile).ExtractErr()
if err != nil {
return diag.Errorf("Error while uploading file %q: %s", imgFilePath, err)
}
}
//wait for active
stateConf := &resource.StateChangeConf{
Pending: []string{string(images.ImageStatusQueued), string(images.ImageStatusSaving), string(images.ImageStatusImporting)},
Target: []string{string(images.ImageStatusActive)},
Refresh: resourceImagesImageV2RefreshFunc(imageClient, d.Id()),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
if _, err = stateConf.WaitForStateContext(ctx); err != nil {
return diag.Errorf("Error waiting for Image: %s", err)
}
img, err := images.Get(imageClient, d.Id()).Extract()
if err != nil {
return diag.FromErr(CheckDeleted(d, err, "image"))
}
if v, ok := d.GetOkExists("verify_checksum"); !useWebDownload && (!ok || (ok && v.(bool))) {
if img.Checksum != fileChecksum {
return diag.Errorf("Error wrong checksum: got %q, expected %q", img.Checksum, fileChecksum)
}
}
d.Partial(false)
return resourceImagesImageV2Read(ctx, d, meta)
}
func resourceImagesImageV2Read(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*Config)
imageClient, err := config.ImageV2Client(GetRegion(d, config))
if err != nil {
return diag.Errorf("Error creating OpenStack image client: %s", err)
}
img, err := images.Get(imageClient, d.Id()).Extract()
if err != nil {
return diag.FromErr(CheckDeleted(d, err, "image"))
}
log.Printf("[DEBUG] Retrieved Image %s: %#v", d.Id(), img)
d.Set("owner", img.Owner)
d.Set("status", img.Status)
d.Set("file", img.File)
d.Set("schema", img.Schema)
d.Set("checksum", img.Checksum)
d.Set("size_bytes", img.SizeBytes)
d.Set("metadata", img.Metadata)
d.Set("created_at", img.CreatedAt.Format(time.RFC3339))
d.Set("updated_at", img.UpdatedAt.Format(time.RFC3339))
d.Set("container_format", img.ContainerFormat)
d.Set("disk_format", img.DiskFormat)
d.Set("min_disk_gb", img.MinDiskGigabytes)
d.Set("min_ram_mb", img.MinRAMMegabytes)
d.Set("image_id", img.ID)
d.Set("file", img.File)
d.Set("name", img.Name)
d.Set("protected", img.Protected)
d.Set("hidden", img.Hidden)
d.Set("size_bytes", img.SizeBytes)
d.Set("tags", img.Tags)
d.Set("visibility", img.Visibility)
d.Set("region", GetRegion(d, config))
// Deprecated
d.Set("update_at", img.UpdatedAt.Format(time.RFC3339))
properties := resourceImagesImageV2ExpandProperties(img.Properties)
if err := d.Set("properties", properties); err != nil {
log.Printf("[WARN] unable to set properties for image %s: %s", img.ID, err)
}
return nil
}
func resourceImagesImageV2Update(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*Config)
imageClient, err := config.ImageV2Client(GetRegion(d, config))
if err != nil {
return diag.Errorf("Error creating OpenStack image client: %s", err)
}
updateOpts := make(images.UpdateOpts, 0)
if d.HasChange("visibility") {
visibility := resourceImagesImageV2VisibilityFromString(d.Get("visibility").(string))
v := images.UpdateVisibility{Visibility: visibility}
updateOpts = append(updateOpts, v)
}
if d.HasChange("protected") {
protected := d.Get("protected").(bool)
v := images.ReplaceImageProtected{NewProtected: protected}
updateOpts = append(updateOpts, v)
}
if d.HasChange("hidden") {
hidden := d.Get("hidden").(bool)
v := images.ReplaceImageHidden{NewHidden: hidden}
updateOpts = append(updateOpts, v)
}
if d.HasChange("min_disk_gb") {
minDiskGb := d.Get("min_disk_gb").(int)
v := images.ReplaceImageMinDisk{NewMinDisk: minDiskGb}
updateOpts = append(updateOpts, v)
}
if d.HasChange("min_ram_mb") {
minRAMMb := d.Get("min_ram_mb").(int)
v := images.ReplaceImageMinRam{NewMinRam: minRAMMb}
updateOpts = append(updateOpts, v)
}
if d.HasChange("name") {
v := images.ReplaceImageName{NewName: d.Get("name").(string)}
updateOpts = append(updateOpts, v)
}
if d.HasChange("tags") {
tags := d.Get("tags").(*schema.Set).List()
v := images.ReplaceImageTags{
NewTags: resourceImagesImageV2BuildTags(tags),
}
updateOpts = append(updateOpts, v)
}
if d.HasChange("properties") {
o, n := d.GetChange("properties")
oldProperties := resourceImagesImageV2ExpandProperties(o.(map[string]interface{}))
newProperties := resourceImagesImageV2ExpandProperties(n.(map[string]interface{}))
// Check for new and changed properties
for newKey, newValue := range newProperties {
var changed bool
oldValue, found := oldProperties[newKey]
if found && (newValue != oldValue) {
changed = true
}
// os_ keys are provided by the OpenStack Image service.
// These are read-only properties that cannot be modified.
// Ignore them here and let CustomizeDiff handle them.
if strings.HasPrefix(newKey, "os_") {
found = true
changed = false
}
// stores is provided by the OpenStack Image service.
// This is a read-only property that cannot be modified.
// Ignore it here and let CustomizeDiff handle it.
if newKey == "stores" {
found = true
changed = false
}
// direct_url is provided by some storage drivers.
// This is a read-only property that cannot be modified.
// Ignore it here and let CustomizeDiff handle it.
if newKey == "direct_url" {
found = true
changed = false
}
if !found {
v := images.UpdateImageProperty{
Op: images.AddOp,
Name: newKey,
Value: newValue,
}
updateOpts = append(updateOpts, v)
}
if found && changed {
v := images.UpdateImageProperty{
Op: images.ReplaceOp,
Name: newKey,
Value: newValue,
}
updateOpts = append(updateOpts, v)
}
}
// Check for removed properties
for oldKey := range oldProperties {
_, found := newProperties[oldKey]
if !found {
v := images.UpdateImageProperty{
Op: images.RemoveOp,
Name: oldKey,
}
updateOpts = append(updateOpts, v)
}
}
}
log.Printf("[DEBUG] Update Options: %#v", updateOpts)
_, err = images.Update(imageClient, d.Id(), updateOpts).Extract()
if err != nil {
return diag.Errorf("Error updating image: %s", err)
}
return resourceImagesImageV2Read(ctx, d, meta)
}
func resourceImagesImageV2Delete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := meta.(*Config)
imageClient, err := config.ImageV2Client(GetRegion(d, config))
if err != nil {
return diag.Errorf("Error creating OpenStack image client: %s", err)
}
log.Printf("[DEBUG] Deleting Image %s", d.Id())
if err := images.Delete(imageClient, d.Id()).Err; err != nil {
return diag.Errorf("Error deleting Image: %s", err)
}
d.SetId("")
return nil
}