-
Notifications
You must be signed in to change notification settings - Fork 649
/
resource_ibm_is_instance_volume_attachment.go
810 lines (743 loc) · 27.8 KB
/
resource_ibm_is_instance_volume_attachment.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
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package vpc
import (
"context"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate"
"github.com/IBM/vpc-go-sdk/vpcv1"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
const (
isInstanceId = "instance"
isInstanceVolAttVol = "volume"
isInstanceVolAttTags = "tags"
isInstanceVolAttId = "volume_attachment_id"
isInstanceVolAttIops = "volume_iops"
isInstanceExistingVolume = "existing"
isInstanceVolAttName = "name"
isInstanceVolAttVolume = "volume"
isInstanceVolumeDeleteOnInstanceDelete = "delete_volume_on_instance_delete"
isInstanceVolumeDeleteOnAttachmentDelete = "delete_volume_on_attachment_delete"
isInstanceVolCapacity = "capacity"
isInstanceVolIops = "iops"
isInstanceVolEncryptionKey = "encryption_key"
isInstanceVolProfile = "profile"
)
func ResourceIBMISInstanceVolumeAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceIBMisInstanceVolumeAttachmentCreate,
Read: resourceIBMisInstanceVolumeAttachmentRead,
Update: resourceIBMisInstanceVolumeAttachmentUpdate,
Delete: resourceIBMisInstanceVolumeAttachmentDelete,
Exists: resourceIBMisInstanceVolumeAttachmentExists,
Importer: &schema.ResourceImporter{},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
CustomizeDiff: customdiff.All(
customdiff.Sequence(
func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error {
return flex.ResourceVolumeValidate(diff)
}),
customdiff.Sequence(
func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error {
return flex.ResourceTagsCustomizeDiff(diff)
}),
),
Schema: map[string]*schema.Schema{
isInstanceId: {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.InvokeValidator("ibm_is_instance_volume_attachment", isInstanceId),
Description: "Instance id",
},
isInstanceVolAttId: {
Type: schema.TypeString,
Computed: true,
Description: "The unique identifier for this volume attachment",
},
isInstanceVolAttName: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validate.InvokeValidator("ibm_is_instance_volume_attachment", isInstanceVolAttName),
Description: "The user-defined name for this volume attachment.",
},
isInstanceVolumeDeleteOnInstanceDelete: {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: "If set to true, when deleting the instance the volume will also be deleted.",
},
isInstanceVolumeDeleteOnAttachmentDelete: {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "If set to true, when deleting the attachment, the volume will also be deleted. Default value for this true.",
},
isInstanceVolAttVol: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{isInstanceVolIops, isInstanceVolumeAttVolumeReferenceName, isInstanceVolProfile, isInstanceVolCapacity, isInstanceVolumeSnapshot, isInstanceVolAttTags},
ValidateFunc: validate.InvokeValidator("ibm_is_instance_volume_attachment", isInstanceName),
Description: "Instance id",
},
isInstanceVolIops: {
Type: schema.TypeInt,
Computed: true,
Optional: true,
ConflictsWith: []string{isInstanceVolAttVol},
Description: "The maximum I/O operations per second (IOPS) for the volume.",
},
isInstanceVolumeAttVolumeReferenceName: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validate.InvokeValidator("ibm_is_instance_volume_attachment", isInstanceVolumeAttVolumeReferenceName),
Description: "The unique user-defined name for this volume",
},
isInstanceVolAttTags: {
Type: schema.TypeSet,
Optional: true,
Computed: true,
ConflictsWith: []string{isInstanceVolAttVol},
Elem: &schema.Schema{Type: schema.TypeString, ValidateFunc: validate.InvokeValidator("ibm_is_instance_volume_attachment", "tags")},
Set: flex.ResourceIBMVPCHash,
Description: "UserTags for the volume instance",
},
isInstanceVolProfile: {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{isInstanceVolAttVol},
Computed: true,
ValidateFunc: validate.InvokeValidator("ibm_is_instance_volume_attachment", isInstanceVolProfile),
Description: "The globally unique name for the volume profile to use for this volume.",
},
isInstanceVolCapacity: {
Type: schema.TypeInt,
Optional: true,
Computed: true,
AtLeastOneOf: []string{isInstanceVolAttVol, isInstanceVolCapacity, isInstanceVolumeSnapshot},
ConflictsWith: []string{isInstanceVolAttVol},
ValidateFunc: validate.InvokeValidator("ibm_is_instance_volume_attachment", isInstanceVolCapacity),
Description: "The capacity of the volume in gigabytes. The specified minimum and maximum capacity values for creating or updating volumes may expand in the future.",
},
isInstanceVolEncryptionKey: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: "The CRN of the [Key Protect Root Key](https://cloud.ibm.com/docs/key-protect?topic=key-protect-getting-started-tutorial) or [Hyper Protect Crypto Service Root Key](https://cloud.ibm.com/docs/hs-crypto?topic=hs-crypto-get-started) for this resource.",
},
isInstanceVolumeSnapshot: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
AtLeastOneOf: []string{isInstanceVolAttVol, isInstanceVolCapacity, isInstanceVolumeSnapshot},
ConflictsWith: []string{isInstanceVolAttVol},
Description: "The snapshot of the volume to be attached",
},
isInstanceVolumeAttVolumeReferenceCrn: {
Type: schema.TypeString,
Computed: true,
Description: "The CRN for this volume",
},
isInstanceVolumeAttVolumeReferenceDeleted: {
Type: schema.TypeString,
Computed: true,
Description: "Link to documentation about deleted resources",
},
isInstanceVolumeAttVolumeReferenceHref: {
Type: schema.TypeString,
Computed: true,
Description: "The URL for this volume",
},
isInstanceVolumeAttDevice: {
Type: schema.TypeString,
Computed: true,
Description: "A unique identifier for the device which is exposed to the instance operating system",
},
isInstanceVolumeAttHref: {
Type: schema.TypeString,
Computed: true,
Description: "The URL for this volume attachment",
},
isInstanceVolumeAttStatus: {
Type: schema.TypeString,
Computed: true,
Description: "The status of this volume attachment, one of [ attached, attaching, deleting, detaching ]",
},
isInstanceVolumeAttType: {
Type: schema.TypeString,
Computed: true,
Description: "The type of volume attachment one of [ boot, data ]",
},
"version": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
}
}
func ResourceIBMISInstanceVolumeAttachmentValidator() *validate.ResourceValidator {
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: isInstanceId,
ValidateFunctionIdentifier: validate.ValidateNoZeroValues,
Type: validate.TypeString})
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: isInstanceVolAttName,
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Optional: true,
Regexp: `^([a-z]|[a-z][-a-z0-9]*[a-z0-9])$`,
MinValueLength: 1,
MaxValueLength: 63})
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: isInstanceVolCapacity,
ValidateFunctionIdentifier: validate.IntBetween,
Type: validate.TypeInt,
MinValue: "10",
MaxValue: "16000"})
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: isInstanceVolumeAttVolumeReferenceName,
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Optional: true,
Regexp: `^([a-z]|[a-z][-a-z0-9]*[a-z0-9])$`,
MinValueLength: 1,
MaxValueLength: 63})
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: isInstanceVolProfile,
ValidateFunctionIdentifier: validate.ValidateAllowedStringValue,
Type: validate.TypeString,
Optional: true,
AllowedValues: "general-purpose, 5iops-tier, 10iops-tier, custom",
})
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: "tags",
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Optional: true,
Regexp: `^[A-Za-z0-9:_ .-]+$`,
MinValueLength: 1,
MaxValueLength: 128})
ibmISInstanceVolumeAttachmentValidator := validate.ResourceValidator{ResourceName: "ibm_is_instance_volume_attachment", Schema: validateSchema}
return &ibmISInstanceVolumeAttachmentValidator
}
func instanceVolAttachmentCreate(d *schema.ResourceData, meta interface{}, instanceId string) error {
sess, err := vpcClient(meta)
if err != nil {
return err
}
instanceVolAttproto := &vpcv1.CreateInstanceVolumeAttachmentOptions{
InstanceID: &instanceId,
}
volumeIdStr := ""
if volumeId, ok := d.GetOk(isInstanceVolAttVol); ok {
volumeIdStr = volumeId.(string)
}
if volumeIdStr != "" {
var volProtoVol = &vpcv1.VolumeAttachmentPrototypeVolumeVolumeIdentity{}
volProtoVol.ID = &volumeIdStr
instanceVolAttproto.Volume = volProtoVol
} else {
var volProtoVol = &vpcv1.VolumeAttachmentPrototypeVolumeVolumePrototypeInstanceContext{}
if volname, ok := d.GetOk(isInstanceVolumeAttVolumeReferenceName); ok {
volnamestr := volname.(string)
volProtoVol.Name = &volnamestr
}
var userTags *schema.Set
if v, ok := d.GetOk(isInstanceVolAttTags); ok {
userTags = v.(*schema.Set)
if userTags != nil && userTags.Len() != 0 {
userTagsArray := make([]string, userTags.Len())
for i, userTag := range userTags.List() {
userTagStr := userTag.(string)
userTagsArray[i] = userTagStr
}
schematicTags := os.Getenv("IC_ENV_TAGS")
var envTags []string
if schematicTags != "" {
envTags = strings.Split(schematicTags, ",")
userTagsArray = append(userTagsArray, envTags...)
}
volProtoVol.UserTags = userTagsArray
}
}
volSnapshotStr := ""
if volSnapshot, ok := d.GetOk(isInstanceVolumeSnapshot); ok {
volSnapshotStr = volSnapshot.(string)
volProtoVol.SourceSnapshot = &vpcv1.SnapshotIdentity{
ID: &volSnapshotStr,
}
}
encryptionCRNStr := ""
if encryptionCRN, ok := d.GetOk(isInstanceVolEncryptionKey); ok {
encryptionCRNStr = encryptionCRN.(string)
volProtoVol.EncryptionKey = &vpcv1.EncryptionKeyIdentity{
CRN: &encryptionCRNStr,
}
}
var snapCapacity int64
if volSnapshotStr != "" {
snapshotGet, _, err := sess.GetSnapshot(&vpcv1.GetSnapshotOptions{
ID: &volSnapshotStr,
})
if err != nil {
return fmt.Errorf("[ERROR] Error while getting snapshot details %q for instance %s: %q", volSnapshotStr, d.Id(), err)
}
snapCapacity = int64(int(*snapshotGet.MinimumCapacity))
}
var volCapacityInt int64
if volCapacity, ok := d.GetOk(isInstanceVolCapacity); ok {
volCapacityInt = int64(volCapacity.(int))
if volCapacityInt != 0 && volCapacityInt > snapCapacity {
volProtoVol.Capacity = &volCapacityInt
}
}
var iops int64
if volIops, ok := d.GetOk(isInstanceVolIops); ok {
iops = int64(volIops.(int))
if iops != 0 {
volProtoVol.Iops = &iops
}
volProfileStr := "custom"
volProtoVol.Profile = &vpcv1.VolumeProfileIdentity{
Name: &volProfileStr,
}
} else {
volProfileStr := "general-purpose"
if volProfile, ok := d.GetOk(isInstanceVolProfile); ok {
volProfileStr = volProfile.(string)
volProtoVol.Profile = &vpcv1.VolumeProfileIdentity{
Name: &volProfileStr,
}
} else {
volProtoVol.Profile = &vpcv1.VolumeProfileIdentity{
Name: &volProfileStr,
}
}
}
instanceVolAttproto.Volume = volProtoVol
}
if autoDelete, ok := d.GetOk(isInstanceVolumeDeleteOnInstanceDelete); ok {
autoDeleteBool := autoDelete.(bool)
instanceVolAttproto.DeleteVolumeOnInstanceDelete = &autoDeleteBool
}
if name, ok := d.GetOk(isInstanceVolAttName); ok {
namestr := name.(string)
instanceVolAttproto.Name = &namestr
}
isInstanceKey := "instance_key_" + instanceId
conns.IbmMutexKV.Lock(isInstanceKey)
defer conns.IbmMutexKV.Unlock(isInstanceKey)
instanceVolAtt, response, err := sess.CreateInstanceVolumeAttachment(instanceVolAttproto)
if err != nil {
log.Printf("[DEBUG] Instance volume attachment create err %s\n%s", err, response)
return fmt.Errorf("[ERROR] Error while attaching volume for instance %s: %q", instanceId, err)
}
d.SetId(makeTerraformVolAttID(instanceId, *instanceVolAtt.ID))
_, err = isWaitForInstanceVolumeAttached(sess, d, instanceId, *instanceVolAtt.ID)
if err != nil {
return err
}
log.Printf("[INFO] Instance (%s) volume attachment : %s", instanceId, *instanceVolAtt.ID)
return nil
}
func resourceIBMisInstanceVolumeAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
instanceId := d.Get(isInstanceId).(string)
err := instanceVolAttachmentCreate(d, meta, instanceId)
if err != nil {
return err
}
return resourceIBMisInstanceVolumeAttachmentRead(d, meta)
}
func resourceIBMisInstanceVolumeAttachmentRead(d *schema.ResourceData, meta interface{}) error {
instanceID, id, err := parseVolAttTerraformID(d.Id())
if err != nil {
return err
}
err = instanceVolumeAttachmentGet(d, meta, instanceID, id)
if err != nil {
return err
}
return nil
}
func instanceVolumeAttachmentGet(d *schema.ResourceData, meta interface{}, instanceId, id string) error {
instanceC, err := vpcClient(meta)
if err != nil {
return err
}
getinsVolAttOptions := &vpcv1.GetInstanceVolumeAttachmentOptions{
InstanceID: &instanceId,
ID: &id,
}
volumeAtt, response, err := instanceC.GetInstanceVolumeAttachment(getinsVolAttOptions)
if err != nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return nil
}
return fmt.Errorf("[ERROR] Error getting Instance volume attachment : %s\n%s", err, response)
}
d.Set(isInstanceId, instanceId)
if volumeAtt.Volume != nil {
d.Set(isInstanceVolumeAttVolumeReferenceName, *volumeAtt.Volume.Name)
d.Set(isInstanceVolumeAttVolumeReferenceCrn, *volumeAtt.Volume.CRN)
if volumeAtt.Volume.Deleted != nil {
d.Set(isInstanceVolumeAttVolumeReferenceDeleted, *volumeAtt.Volume.Deleted.MoreInfo)
}
d.Set(isInstanceVolumeAttVolumeReferenceHref, *volumeAtt.Volume.Href)
}
d.Set(isInstanceVolumeDeleteOnInstanceDelete, *volumeAtt.DeleteVolumeOnInstanceDelete)
d.Set(isInstanceVolAttName, *volumeAtt.Name)
if volumeAtt.Device != nil {
d.Set(isInstanceVolumeAttDevice, *volumeAtt.Device.ID)
}
d.Set(isInstanceVolumeAttHref, *volumeAtt.Href)
d.Set(isInstanceVolAttId, *volumeAtt.ID)
d.Set(isInstanceVolumeAttStatus, *volumeAtt.Status)
d.Set(isInstanceVolumeAttType, *volumeAtt.Type)
if err = d.Set("version", response.Headers.Get("Etag")); err != nil {
return fmt.Errorf("Error setting version: %s", err)
}
volId := *volumeAtt.Volume.ID
getVolOptions := &vpcv1.GetVolumeOptions{
ID: &volId,
}
volumeDetail, _, err := instanceC.GetVolume(getVolOptions)
if err != nil || volumeDetail == nil {
return fmt.Errorf("[ERROR] Error while getting volume details of volume %s ", id)
}
d.Set(isInstanceVolAttVol, *volumeDetail.ID)
d.Set(isInstanceVolIops, *volumeDetail.Iops)
d.Set(isInstanceVolProfile, *volumeDetail.Profile.Name)
d.Set(isInstanceVolCapacity, *volumeDetail.Capacity)
if volumeDetail.EncryptionKey != nil {
d.Set(isInstanceVolEncryptionKey, *volumeDetail.EncryptionKey.CRN)
}
if volumeDetail.SourceSnapshot != nil {
d.Set(isInstanceVolumeSnapshot, *volumeDetail.SourceSnapshot.ID)
}
return nil
}
func instanceVolAttUpdate(d *schema.ResourceData, meta interface{}) error {
instanceC, err := vpcClient(meta)
if err != nil {
return err
}
instanceId, id, err := parseVolAttTerraformID(d.Id())
if err != nil {
return err
}
updateInstanceVolAttOptions := &vpcv1.UpdateInstanceVolumeAttachmentOptions{
InstanceID: &instanceId,
ID: &id,
}
flag := false
// name && auto delete change
volAttNamePatchModel := &vpcv1.VolumeAttachmentPatch{}
if d.HasChange(isInstanceVolumeDeleteOnInstanceDelete) {
autoDelete := d.Get(isInstanceVolumeDeleteOnInstanceDelete).(bool)
volAttNamePatchModel.DeleteVolumeOnInstanceDelete = &autoDelete
flag = true
}
if d.HasChange(isInstanceVolAttName) {
name := d.Get(isInstanceVolAttName).(string)
volAttNamePatchModel.Name = &name
flag = true
}
if flag {
volAttNamePatchModelAsPatch, err := volAttNamePatchModel.AsPatch()
if err != nil || volAttNamePatchModelAsPatch == nil {
return fmt.Errorf("[ERROR] Error Instance volume attachment (%s) as patch : %s", id, err)
}
updateInstanceVolAttOptions.VolumeAttachmentPatch = volAttNamePatchModelAsPatch
instanceVolAttUpdate, response, err := instanceC.UpdateInstanceVolumeAttachment(updateInstanceVolAttOptions)
if err != nil || instanceVolAttUpdate == nil {
log.Printf("[DEBUG] Instance volume attachment updation err %s\n%s", err, response)
return err
}
}
if d.HasChange(isInstanceVolumeAttVolumeReferenceName) {
newname := d.Get(isInstanceVolumeAttVolumeReferenceName).(string)
volid := d.Get(isInstanceVolAttVol).(string)
voloptions := &vpcv1.UpdateVolumeOptions{
ID: &volid,
}
volumePatchModel := &vpcv1.VolumePatch{
Name: &newname,
}
volumePatch, err := volumePatchModel.AsPatch()
if err != nil {
return fmt.Errorf("[ERROR] Error calling asPatch for VolumePatch: %s", err)
}
voloptions.VolumePatch = volumePatch
_, response, err := instanceC.UpdateVolume(voloptions)
if err != nil {
return fmt.Errorf("[ERROR] Error updating volume name : %s\n%s", err, response)
}
}
// profile/iops update
volId := ""
if volIdOk, ok := d.GetOk(isInstanceVolAttVol); ok {
volId = volIdOk.(string)
}
if volId != "" && (d.HasChange(isInstanceVolIops) || d.HasChange(isInstanceVolProfile) || d.HasChange(isInstanceVolAttTags)) {
insId := d.Get(isInstanceId).(string)
getinsOptions := &vpcv1.GetInstanceOptions{
ID: &insId,
}
instance, response, err := instanceC.GetInstance(getinsOptions)
if err != nil || instance == nil {
return fmt.Errorf("[ERROR] Error retrieving Instance (%s) : %s\n%s", insId, err, response)
}
if instance != nil && *instance.Status != "running" {
actiontype := "start"
createinsactoptions := &vpcv1.CreateInstanceActionOptions{
InstanceID: &insId,
Type: &actiontype,
}
_, response, err = instanceC.CreateInstanceAction(createinsactoptions)
if err != nil {
return fmt.Errorf("[ERROR] Error starting Instance (%s) : %s\n%s", insId, err, response)
}
_, err = isWaitForInstanceAvailable(instanceC, insId, d.Timeout(schema.TimeoutCreate), d)
if err != nil {
return err
}
}
updateVolumeProfileOptions := &vpcv1.UpdateVolumeOptions{
ID: &volId,
}
volumeProfilePatchModel := &vpcv1.VolumePatch{}
if d.HasChange(isInstanceVolProfile) {
profile := d.Get(isInstanceVolProfile).(string)
volumeProfilePatchModel.Profile = &vpcv1.VolumeProfileIdentity{
Name: &profile,
}
} else if d.HasChange(isVolumeIops) {
profile := d.Get(isInstanceVolProfile).(string)
volumeProfilePatchModel.Profile = &vpcv1.VolumeProfileIdentity{
Name: &profile,
}
iops := int64(d.Get(isVolumeIops).(int))
volumeProfilePatchModel.Iops = &iops
}
if d.HasChange(isInstanceVolAttTags) && !d.IsNewResource() {
if v, ok := d.GetOk(isInstanceVolAttTags); ok {
userTags := v.(*schema.Set)
if userTags != nil && userTags.Len() != 0 {
userTagsArray := make([]string, userTags.Len())
for i, userTag := range userTags.List() {
userTagStr := userTag.(string)
userTagsArray[i] = userTagStr
}
schematicTags := os.Getenv("IC_ENV_TAGS")
var envTags []string
if schematicTags != "" {
envTags = strings.Split(schematicTags, ",")
userTagsArray = append(userTagsArray, envTags...)
}
volumeProfilePatchModel.UserTags = userTagsArray
}
}
}
volumeProfilePatch, err := volumeProfilePatchModel.AsPatch()
if err != nil {
return fmt.Errorf("[ERROR] Error calling asPatch for volumeProfilePatch: %s", err)
}
optionsget := &vpcv1.GetVolumeOptions{
ID: &volId,
}
_, response, err = instanceC.GetVolume(optionsget)
if err != nil {
return fmt.Errorf("[ERROR] Error getting Boot Volume (%s): %s\n%s", id, err, response)
}
eTag := response.Headers.Get("ETag")
updateVolumeProfileOptions.IfMatch = &eTag
updateVolumeProfileOptions.VolumePatch = volumeProfilePatch
_, response, err = instanceC.UpdateVolume(updateVolumeProfileOptions)
if err != nil {
return fmt.Errorf("[ERROR] Error updating volume profile/iops/userTags: %s\n%s", err, response)
}
isWaitForVolumeAvailable(instanceC, volId, d.Timeout(schema.TimeoutCreate))
}
// capacity update
if volId != "" && d.HasChange(isInstanceVolCapacity) {
getvolumeoptions := &vpcv1.GetVolumeOptions{
ID: &volId,
}
vol, response, err := instanceC.GetVolume(getvolumeoptions)
if err != nil {
return fmt.Errorf("[ERROR] Error Getting Volume (%s): %s\n%s", id, err, response)
}
if vol.VolumeAttachments == nil || len(vol.VolumeAttachments) == 0 || *vol.VolumeAttachments[0].Name == "" {
return fmt.Errorf("[ERROR] Error volume capacity can't be updated since volume %s is not attached to any instance for VolumePatch", id)
}
getinsOptions := &vpcv1.GetInstanceOptions{
ID: &instanceId,
}
instance, response, err := instanceC.GetInstance(getinsOptions)
if err != nil || instance == nil {
return fmt.Errorf("[ERROR] Error retrieving Instance (%s) : %s\n%s", instanceId, err, response)
}
if instance != nil && *instance.Status != "running" {
actiontype := "start"
createinsactoptions := &vpcv1.CreateInstanceActionOptions{
InstanceID: &instanceId,
Type: &actiontype,
}
_, response, err = instanceC.CreateInstanceAction(createinsactoptions)
if err != nil {
return fmt.Errorf("[ERROR] Error starting Instance (%s) : %s\n%s", instanceId, err, response)
}
_, err = isWaitForInstanceAvailable(instanceC, instanceId, d.Timeout(schema.TimeoutCreate), d)
return fmt.Errorf("[ERROR] Error starting Instance (%s) : %s\n%s", instanceId, err, response)
}
capacity := int64(d.Get(isVolumeCapacity).(int))
updateVolumeOptions := &vpcv1.UpdateVolumeOptions{
ID: &volId,
}
volumeCapacityPatchModel := &vpcv1.VolumePatch{}
volumeCapacityPatchModel.Capacity = &capacity
volumeCapacityPatch, err := volumeCapacityPatchModel.AsPatch()
if err != nil {
return fmt.Errorf("[ERROR] Error calling asPatch for volumeCapacityPatchModel: %s", err)
}
updateVolumeOptions.VolumePatch = volumeCapacityPatch
_, response, err = instanceC.UpdateVolume(updateVolumeOptions)
if err != nil {
return fmt.Errorf("[ERROR] Error updating volume capacity: %s\n%s", err, response)
}
_, err = isWaitForVolumeAvailable(instanceC, volId, d.Timeout(schema.TimeoutCreate))
if err != nil {
return err
}
}
return nil
}
func resourceIBMisInstanceVolumeAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
err := instanceVolAttUpdate(d, meta)
if err != nil {
return err
}
return resourceIBMisInstanceVolumeAttachmentRead(d, meta)
}
func instanceVolAttDelete(d *schema.ResourceData, meta interface{}, instanceId, id, volId string, volDelete bool) error {
instanceC, err := vpcClient(meta)
if err != nil {
return err
}
deleteInstanceVolAttOptions := &vpcv1.DeleteInstanceVolumeAttachmentOptions{
InstanceID: &instanceId,
ID: &id,
}
isInstanceKey := "instance_key_" + instanceId
conns.IbmMutexKV.Lock(isInstanceKey)
defer conns.IbmMutexKV.Unlock(isInstanceKey)
_, err = instanceC.DeleteInstanceVolumeAttachment(deleteInstanceVolAttOptions)
if err != nil {
return fmt.Errorf("[ERROR] Error while deleting volume attachment (%s) from instance (%s) : %q", id, instanceId, err)
}
_, err = isWaitForInstanceVolumeDetached(instanceC, d, instanceId, id)
if err != nil {
return fmt.Errorf("[ERROR] Error while deleting volume attachment (%s) from instance (%s) on wait : %q", id, instanceId, err)
}
if volDelete {
deleteVolumeOptions := &vpcv1.DeleteVolumeOptions{
ID: &volId,
}
response, err := instanceC.DeleteVolume(deleteVolumeOptions)
if err != nil {
return fmt.Errorf("[ERROR] Error while deleting volume : %s\n%s", err, response)
}
_, err = isWaitForVolumeDeleted(instanceC, volId, d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
}
return nil
}
func resourceIBMisInstanceVolumeAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
instanceId, id, err := parseVolAttTerraformID(d.Id())
if err != nil {
return err
}
volDelete := false
if volDeleteOk, ok := d.GetOk(isInstanceVolumeDeleteOnAttachmentDelete); ok {
volDelete = volDeleteOk.(bool)
}
volId := ""
if volIdOk, ok := d.GetOk(isInstanceVolAttVol); ok {
volId = volIdOk.(string)
}
err = instanceVolAttDelete(d, meta, instanceId, id, volId, volDelete)
if err != nil {
return err
}
d.SetId("")
return nil
}
func resourceIBMisInstanceVolumeAttachmentExists(d *schema.ResourceData, meta interface{}) (bool, error) {
instanceId, id, err := parseVolAttTerraformID(d.Id())
if err != nil {
return false, err
}
exists, err := instanceVolAttExists(d, meta, instanceId, id)
return exists, err
}
func instanceVolAttExists(d *schema.ResourceData, meta interface{}, instanceId, id string) (bool, error) {
instanceC, err := vpcClient(meta)
if err != nil {
return false, err
}
getinsvolattOptions := &vpcv1.GetInstanceVolumeAttachmentOptions{
InstanceID: &instanceId,
ID: &id,
}
_, response, err := instanceC.GetInstanceVolumeAttachment(getinsvolattOptions)
if err != nil {
if response != nil && response.StatusCode == 404 {
return false, nil
}
return false, fmt.Errorf("[ERROR] Error getting Instance volume attachment: %s\n%s", err, response)
}
return true, nil
}
func makeTerraformVolAttID(id1, id2 string) string {
// Include both instance id and volume attachment to create a unique Terraform id. As a bonus,
// we can extract the instance id as needed for API calls such as READ.
return fmt.Sprintf("%s/%s", id1, id2)
}
func parseVolAttTerraformID(s string) (string, string, error) {
segments := strings.Split(s, "/")
if len(segments) != 2 {
return "", "", fmt.Errorf("invalid terraform Id %s (incorrect number of segments)", s)
}
if segments[0] == "" || segments[1] == "" {
return "", "", fmt.Errorf("invalid terraform Id %s (one or more empty segments)", s)
}
return segments[0], segments[1], nil
}