forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresource_compute_disk.go
1226 lines (1081 loc) · 37.7 KB
/
resource_compute_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
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
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------
package google
import (
"fmt"
"log"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform/helper/customdiff"
"github.com/hashicorp/terraform/helper/schema"
compute "google.golang.org/api/compute/v1"
"google.golang.org/api/googleapi"
)
const (
computeDiskUserRegexString = "^(?:https://www.googleapis.com/compute/v1/projects/)?(" + ProjectRegex + ")/zones/([-_a-zA-Z0-9]*)/instances/([-_a-zA-Z0-9]*)$"
)
var (
computeDiskUserRegex = regexp.MustCompile(computeDiskUserRegexString)
)
// Is the new disk size smaller than the old one?
func isDiskShrinkage(old, new, _ interface{}) bool {
// It's okay to remove size entirely.
if old == nil || new == nil {
return false
}
return new.(int) < old.(int)
}
// We cannot suppress the diff for the case when family name is not part of the image name since we can't
// make a network call in a DiffSuppressFunc.
func diskImageDiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
// Understand that this function solves a messy problem ("how do we tell if the diff between two images
// is 'ForceNew-worthy', without making a network call?") in the best way we can: through a series of special
// cases and regexes. If you find yourself here because you are trying to add a new special case,
// you are probably looking for the diskImageFamilyEquals function and its subfunctions.
// In order to keep this maintainable, we need to ensure that the positive and negative examples
// in resource_compute_disk_test.go are as complete as possible.
// 'old' is read from the API.
// It always has the format 'https://www.googleapis.com/compute/v1/projects/(%s)/global/images/(%s)'
matches := resolveImageLink.FindStringSubmatch(old)
if matches == nil {
// Image read from the API doesn't have the expected format. In practice, it should never happen
return false
}
oldProject := matches[1]
oldName := matches[2]
// Partial or full self link family
if resolveImageProjectFamily.MatchString(new) {
// Value matches pattern "projects/{project}/global/images/family/{family-name}$"
matches := resolveImageProjectFamily.FindStringSubmatch(new)
newProject := matches[1]
newFamilyName := matches[2]
return diskImageProjectNameEquals(oldProject, newProject) && diskImageFamilyEquals(oldName, newFamilyName)
}
// Partial or full self link image
if resolveImageProjectImage.MatchString(new) {
// Value matches pattern "projects/{project}/global/images/{image-name}$"
matches := resolveImageProjectImage.FindStringSubmatch(new)
newProject := matches[1]
newImageName := matches[2]
return diskImageProjectNameEquals(oldProject, newProject) && diskImageEquals(oldName, newImageName)
}
// Partial link without project family
if resolveImageGlobalFamily.MatchString(new) {
// Value is "global/images/family/{family-name}"
matches := resolveImageGlobalFamily.FindStringSubmatch(new)
familyName := matches[1]
return diskImageFamilyEquals(oldName, familyName)
}
// Partial link without project image
if resolveImageGlobalImage.MatchString(new) {
// Value is "global/images/{image-name}"
matches := resolveImageGlobalImage.FindStringSubmatch(new)
imageName := matches[1]
return diskImageEquals(oldName, imageName)
}
// Family shorthand
if resolveImageFamilyFamily.MatchString(new) {
// Value is "family/{family-name}"
matches := resolveImageFamilyFamily.FindStringSubmatch(new)
familyName := matches[1]
return diskImageFamilyEquals(oldName, familyName)
}
// Shorthand for image or family
if resolveImageProjectImageShorthand.MatchString(new) {
// Value is "{project}/{image-name}" or "{project}/{family-name}"
matches := resolveImageProjectImageShorthand.FindStringSubmatch(new)
newProject := matches[1]
newName := matches[2]
return diskImageProjectNameEquals(oldProject, newProject) &&
(diskImageEquals(oldName, newName) || diskImageFamilyEquals(oldName, newName))
}
// Image or family only
if diskImageEquals(oldName, new) || diskImageFamilyEquals(oldName, new) {
// Value is "{image-name}" or "{family-name}"
return true
}
return false
}
func diskImageProjectNameEquals(project1, project2 string) bool {
// Convert short project name to full name
// For instance, centos => centos-cloud
fullProjectName, ok := imageMap[project2]
if ok {
project2 = fullProjectName
}
return project1 == project2
}
func diskImageEquals(oldImageName, newImageName string) bool {
return oldImageName == newImageName
}
func diskImageFamilyEquals(imageName, familyName string) bool {
// Handles the case when the image name includes the family name
// e.g. image name: debian-9-drawfork-v20180109, family name: debian-9
if strings.Contains(imageName, familyName) {
return true
}
if suppressCanonicalFamilyDiff(imageName, familyName) {
return true
}
if suppressWindowsSqlFamilyDiff(imageName, familyName) {
return true
}
if suppressWindowsFamilyDiff(imageName, familyName) {
return true
}
return false
}
// e.g. image: ubuntu-1404-trusty-v20180122, family: ubuntu-1404-lts
func suppressCanonicalFamilyDiff(imageName, familyName string) bool {
parts := canonicalUbuntuLtsImage.FindStringSubmatch(imageName)
if len(parts) == 3 {
f := fmt.Sprintf("ubuntu-%s%s-lts", parts[1], parts[2])
if f == familyName {
return true
}
}
return false
}
// e.g. image: sql-2017-standard-windows-2016-dc-v20180109, family: sql-std-2017-win-2016
// e.g. image: sql-2017-express-windows-2012-r2-dc-v20180109, family: sql-exp-2017-win-2012-r2
func suppressWindowsSqlFamilyDiff(imageName, familyName string) bool {
parts := windowsSqlImage.FindStringSubmatch(imageName)
if len(parts) == 5 {
edition := parts[2] // enterprise, standard or web.
sqlVersion := parts[1]
windowsVersion := parts[3]
// Translate edition
switch edition {
case "enterprise":
edition = "ent"
case "standard":
edition = "std"
case "express":
edition = "exp"
}
var f string
if revision := parts[4]; revision != "" {
// With revision
f = fmt.Sprintf("sql-%s-%s-win-%s-r%s", edition, sqlVersion, windowsVersion, revision)
} else {
// No revision
f = fmt.Sprintf("sql-%s-%s-win-%s", edition, sqlVersion, windowsVersion)
}
if f == familyName {
return true
}
}
return false
}
// e.g. image: windows-server-1709-dc-core-v20180109, family: windows-1709-core
// e.g. image: windows-server-1709-dc-core-for-containers-v20180109, family: "windows-1709-core-for-containers
func suppressWindowsFamilyDiff(imageName, familyName string) bool {
updatedFamilyString := strings.Replace(familyName, "windows-", "windows-server-", 1)
updatedFamilyString = strings.Replace(updatedFamilyString, "-core", "-dc-core", 1)
if strings.Contains(imageName, updatedFamilyString) {
return true
}
return false
}
func diskEncryptionKeyDiffSuppress(k, old, new string, d *schema.ResourceData) bool {
if strings.HasSuffix(k, "#") {
if old == "1" && new == "0" {
// If we have a disk_encryption_key_raw, we can trust that the diff will be handled there
// and we don't need to worry about it here.
return d.Get("disk_encryption_key_raw").(string) != ""
} else if new == "1" && old == "0" {
// This will be handled by diffing the 'raw_key' attribute.
return true
}
} else if strings.HasSuffix(k, "raw_key") {
disk_key := d.Get("disk_encryption_key_raw").(string)
return disk_key == old && old != "" && new == ""
} else if k == "disk_encryption_key_raw" {
disk_key := d.Get("disk_encryption_key.0.raw_key").(string)
return disk_key == old && old != "" && new == ""
}
return false
}
func resourceComputeDisk() *schema.Resource {
return &schema.Resource{
Create: resourceComputeDiskCreate,
Read: resourceComputeDiskRead,
Update: resourceComputeDiskUpdate,
Delete: resourceComputeDiskDelete,
Importer: &schema.ResourceImporter{
State: resourceComputeDiskImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(300 * time.Second),
Update: schema.DefaultTimeout(240 * time.Second),
Delete: schema.DefaultTimeout(240 * time.Second),
},
CustomizeDiff: customdiff.All(
customdiff.ForceNewIfChange("size", isDiskShrinkage)),
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"labels": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"size": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
Default: "pd-standard",
},
"image": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: diskImageDiffSuppress,
},
"zone": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
},
"source_image_encryption_key": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"raw_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"sha256": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"disk_encryption_key": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
DiffSuppressFunc: diskEncryptionKeyDiffSuppress,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"raw_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"sha256": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"snapshot": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
},
"source_snapshot_encryption_key": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"raw_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"sha256": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"creation_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"label_fingerprint": {
Type: schema.TypeString,
Computed: true,
},
"last_attach_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"last_detach_timestamp": {
Type: schema.TypeString,
Computed: true,
},
"source_image_id": {
Type: schema.TypeString,
Computed: true,
},
"source_snapshot_id": {
Type: schema.TypeString,
Computed: true,
},
"users": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
DiffSuppressFunc: compareSelfLinkOrResourceName,
},
},
"disk_encryption_key_raw": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Sensitive: true,
DiffSuppressFunc: diskEncryptionKeyDiffSuppress,
Deprecated: "Use disk_encryption_key.raw_key instead.",
},
"disk_encryption_key_sha256": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Deprecated: "Use disk_encryption_key.sha256 instead.",
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"self_link": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceComputeDiskCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
obj := make(map[string]interface{})
descriptionProp, err := expandComputeDiskDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
labelsProp, err := expandComputeDiskLabels(d.Get("labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
nameProp, err := expandComputeDiskName(d.Get("name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) {
obj["name"] = nameProp
}
sizeGbProp, err := expandComputeDiskSize(d.Get("size"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("size"); !isEmptyValue(reflect.ValueOf(sizeGbProp)) && (ok || !reflect.DeepEqual(v, sizeGbProp)) {
obj["sizeGb"] = sizeGbProp
}
typeProp, err := expandComputeDiskType(d.Get("type"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("type"); !isEmptyValue(reflect.ValueOf(typeProp)) && (ok || !reflect.DeepEqual(v, typeProp)) {
obj["type"] = typeProp
}
sourceImageProp, err := expandComputeDiskImage(d.Get("image"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("image"); !isEmptyValue(reflect.ValueOf(sourceImageProp)) && (ok || !reflect.DeepEqual(v, sourceImageProp)) {
obj["sourceImage"] = sourceImageProp
}
zoneProp, err := expandComputeDiskZone(d.Get("zone"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("zone"); !isEmptyValue(reflect.ValueOf(zoneProp)) && (ok || !reflect.DeepEqual(v, zoneProp)) {
obj["zone"] = zoneProp
}
sourceImageEncryptionKeyProp, err := expandComputeDiskSourceImageEncryptionKey(d.Get("source_image_encryption_key"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("source_image_encryption_key"); !isEmptyValue(reflect.ValueOf(sourceImageEncryptionKeyProp)) && (ok || !reflect.DeepEqual(v, sourceImageEncryptionKeyProp)) {
obj["sourceImageEncryptionKey"] = sourceImageEncryptionKeyProp
}
diskEncryptionKeyProp, err := expandComputeDiskDiskEncryptionKey(d.Get("disk_encryption_key"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("disk_encryption_key"); !isEmptyValue(reflect.ValueOf(diskEncryptionKeyProp)) && (ok || !reflect.DeepEqual(v, diskEncryptionKeyProp)) {
obj["diskEncryptionKey"] = diskEncryptionKeyProp
}
sourceSnapshotProp, err := expandComputeDiskSnapshot(d.Get("snapshot"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("snapshot"); !isEmptyValue(reflect.ValueOf(sourceSnapshotProp)) && (ok || !reflect.DeepEqual(v, sourceSnapshotProp)) {
obj["sourceSnapshot"] = sourceSnapshotProp
}
sourceSnapshotEncryptionKeyProp, err := expandComputeDiskSourceSnapshotEncryptionKey(d.Get("source_snapshot_encryption_key"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("source_snapshot_encryption_key"); !isEmptyValue(reflect.ValueOf(sourceSnapshotEncryptionKeyProp)) && (ok || !reflect.DeepEqual(v, sourceSnapshotEncryptionKeyProp)) {
obj["sourceSnapshotEncryptionKey"] = sourceSnapshotEncryptionKeyProp
}
obj, err = resourceComputeDiskEncoder(d, meta, obj)
if err != nil {
return err
}
url, err := replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/zones/{{zone}}/disks")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new Disk: %#v", obj)
res, err := sendRequest(config, "POST", url, obj)
if err != nil {
return fmt.Errorf("Error creating Disk: %s", err)
}
// Store the ID now
id, err := replaceVars(d, config, "{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
op := &compute.Operation{}
err = Convert(res, op)
if err != nil {
return err
}
waitErr := computeOperationWaitTime(
config.clientCompute, op, project, "Creating Disk",
int(d.Timeout(schema.TimeoutCreate).Minutes()))
if waitErr != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create Disk: %s", waitErr)
}
log.Printf("[DEBUG] Finished creating Disk %q: %#v", d.Id(), res)
return resourceComputeDiskRead(d, meta)
}
func resourceComputeDiskRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
url, err := replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/zones/{{zone}}/disks/{{name}}")
if err != nil {
return err
}
res, err := sendRequest(config, "GET", url, nil)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("ComputeDisk %q", d.Id()))
}
res, err = resourceComputeDiskDecoder(d, meta, res)
if err != nil {
return err
}
if err := d.Set("label_fingerprint", flattenComputeDiskLabelFingerprint(res["labelFingerprint"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("creation_timestamp", flattenComputeDiskCreationTimestamp(res["creationTimestamp"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("description", flattenComputeDiskDescription(res["description"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("last_attach_timestamp", flattenComputeDiskLastAttachTimestamp(res["lastAttachTimestamp"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("last_detach_timestamp", flattenComputeDiskLastDetachTimestamp(res["lastDetachTimestamp"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("labels", flattenComputeDiskLabels(res["labels"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("name", flattenComputeDiskName(res["name"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("size", flattenComputeDiskSize(res["sizeGb"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("type", flattenComputeDiskType(res["type"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("users", flattenComputeDiskUsers(res["users"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("image", flattenComputeDiskImage(res["sourceImage"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("zone", flattenComputeDiskZone(res["zone"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("source_image_encryption_key", flattenComputeDiskSourceImageEncryptionKey(res["sourceImageEncryptionKey"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("source_image_id", flattenComputeDiskSourceImageId(res["sourceImageId"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("disk_encryption_key", flattenComputeDiskDiskEncryptionKey(res["diskEncryptionKey"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("snapshot", flattenComputeDiskSnapshot(res["sourceSnapshot"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("source_snapshot_encryption_key", flattenComputeDiskSourceSnapshotEncryptionKey(res["sourceSnapshotEncryptionKey"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("source_snapshot_id", flattenComputeDiskSourceSnapshotId(res["sourceSnapshotId"])); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("self_link", ConvertSelfLinkToV1(res["selfLink"].(string))); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Disk: %s", err)
}
return nil
}
func resourceComputeDiskUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
var url string
var res map[string]interface{}
op := &compute.Operation{}
d.Partial(true)
if d.HasChange("label_fingerprint") || d.HasChange("labels") {
obj := make(map[string]interface{})
labelFingerprintProp := d.Get("label_fingerprint")
obj["labelFingerprint"] = labelFingerprintProp
labelsProp, err := expandComputeDiskLabels(d.Get("labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
url, err = replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/zones/{{zone}}/disks/{{name}}/setLabels")
if err != nil {
return err
}
res, err = sendRequest(config, "POST", url, obj)
if err != nil {
return fmt.Errorf("Error updating Disk %q: %s", d.Id(), err)
}
err = Convert(res, op)
if err != nil {
return err
}
err = computeOperationWaitTime(
config.clientCompute, op, project, "Updating Disk",
int(d.Timeout(schema.TimeoutUpdate).Minutes()))
if err != nil {
return err
}
d.SetPartial("label_fingerprint")
d.SetPartial("labels")
}
if d.HasChange("size") {
obj := make(map[string]interface{})
sizeGbProp, err := expandComputeDiskSize(d.Get("size"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("size"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, sizeGbProp)) {
obj["sizeGb"] = sizeGbProp
}
url, err = replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/zones/{{zone}}/disks/{{name}}/resize")
if err != nil {
return err
}
res, err = sendRequest(config, "POST", url, obj)
if err != nil {
return fmt.Errorf("Error updating Disk %q: %s", d.Id(), err)
}
err = Convert(res, op)
if err != nil {
return err
}
err = computeOperationWaitTime(
config.clientCompute, op, project, "Updating Disk",
int(d.Timeout(schema.TimeoutUpdate).Minutes()))
if err != nil {
return err
}
d.SetPartial("size")
}
d.Partial(false)
return resourceComputeDiskRead(d, meta)
}
func resourceComputeDiskDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
url, err := replaceVars(d, config, "https://www.googleapis.com/compute/v1/projects/{{project}}/zones/{{zone}}/disks/{{name}}")
if err != nil {
return err
}
// if disks are attached, they must be detached before the disk can be deleted
if instances, ok := d.Get("users").([]interface{}); ok {
type detachArgs struct{ project, zone, instance, deviceName string }
var detachCalls []detachArgs
self := d.Get("self_link").(string)
for _, instance := range instances {
if !computeDiskUserRegex.MatchString(instance.(string)) {
return fmt.Errorf("Unknown user %q of disk %q", instance, self)
}
matches := computeDiskUserRegex.FindStringSubmatch(instance.(string))
instanceProject := matches[1]
instanceZone := matches[2]
instanceName := matches[3]
i, err := config.clientCompute.Instances.Get(instanceProject, instanceZone, instanceName).Do()
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 {
log.Printf("[WARN] instance %q not found, not bothering to detach disks", instance.(string))
continue
}
return fmt.Errorf("Error retrieving instance %s: %s", instance.(string), err.Error())
}
for _, disk := range i.Disks {
if disk.Source == self {
detachCalls = append(detachCalls, detachArgs{
project: project,
zone: GetResourceNameFromSelfLink(i.Zone),
instance: i.Name,
deviceName: disk.DeviceName,
})
}
}
}
for _, call := range detachCalls {
op, err := config.clientCompute.Instances.DetachDisk(call.project, call.zone, call.instance, call.deviceName).Do()
if err != nil {
return fmt.Errorf("Error detaching disk %s from instance %s/%s/%s: %s", call.deviceName, call.project,
call.zone, call.instance, err.Error())
}
err = computeOperationWait(config.clientCompute, op, call.project,
fmt.Sprintf("Detaching disk from %s/%s/%s", call.project, call.zone, call.instance))
if err != nil {
if opErr, ok := err.(ComputeOperationError); ok && len(opErr.Errors) == 1 && opErr.Errors[0].Code == "RESOURCE_NOT_FOUND" {
log.Printf("[WARN] instance %q was deleted while awaiting detach", call.instance)
continue
}
return err
}
}
}
log.Printf("[DEBUG] Deleting Disk %q", d.Id())
res, err := sendRequest(config, "DELETE", url, nil)
if err != nil {
return handleNotFoundError(err, d, "Disk")
}
op := &compute.Operation{}
err = Convert(res, op)
if err != nil {
return err
}
err = computeOperationWaitTime(
config.clientCompute, op, project, "Deleting Disk",
int(d.Timeout(schema.TimeoutDelete).Minutes()))
if err != nil {
return err
}
log.Printf("[DEBUG] Finished deleting Disk %q: %#v", d.Id(), res)
return nil
}
func resourceComputeDiskImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
parseImportId([]string{"projects/(?P<project>[^/]+)/zones/(?P<zone>[^/]+)/disks/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<zone>[^/]+)/(?P<name>[^/]+)", "(?P<name>[^/]+)"}, d, config)
// Replace import id for the resource id
id, err := replaceVars(d, config, "{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
// In the end, it's possible that someone has tried to import
// a disk using only the region. To find out what zone the
// disk is in, we need to check every zone in the region, to
// see if we can find a disk with the same name. This will
// find the first disk in the specified region with a matching
// name. There might be multiple matching disks - we're not
// considering that an error case here. We don't check for it.
if zone, err := getZone(d, config); err != nil || zone == "" {
project, err := getProject(d, config)
if err != nil {
return nil, err
}
region, err := getRegion(d, config)
if err != nil {
return nil, err
}
getDisk := func(zone string) (interface{}, error) {
return config.clientCompute.Disks.Get(project, zone, d.Id()).Do()
}
resource, err := getZonalResourceFromRegion(getDisk, region, config.clientCompute, project)
if err != nil {
return nil, err
}
d.Set("zone", resource.(*compute.Disk).Zone)
}
return []*schema.ResourceData{d}, nil
}
func flattenComputeDiskLabelFingerprint(v interface{}) interface{} {
return v
}
func flattenComputeDiskCreationTimestamp(v interface{}) interface{} {
return v
}
func flattenComputeDiskDescription(v interface{}) interface{} {
return v
}
func flattenComputeDiskLastAttachTimestamp(v interface{}) interface{} {
return v
}
func flattenComputeDiskLastDetachTimestamp(v interface{}) interface{} {
return v
}
func flattenComputeDiskLabels(v interface{}) interface{} {
return v
}
func flattenComputeDiskName(v interface{}) interface{} {
return v
}
func flattenComputeDiskSize(v interface{}) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
return intVal
} // let terraform core handle it if we can't convert the string to an int.
}
return v
}
func flattenComputeDiskType(v interface{}) interface{} {
if v == nil {
return v
}
return NameFromSelfLinkStateFunc(v)
}
func flattenComputeDiskUsers(v interface{}) interface{} {
if v == nil {
return v
}
return convertAndMapStringArr(v.([]interface{}), ConvertSelfLinkToV1)
}
func flattenComputeDiskImage(v interface{}) interface{} {
return v
}
func flattenComputeDiskZone(v interface{}) interface{} {
if v == nil {
return v
}
return NameFromSelfLinkStateFunc(v)
}
func flattenComputeDiskSourceImageEncryptionKey(v interface{}) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
transformed := make(map[string]interface{})
transformed["raw_key"] =
flattenComputeDiskSourceImageEncryptionKeyRawKey(original["rawKey"])
transformed["sha256"] =
flattenComputeDiskSourceImageEncryptionKeySha256(original["sha256"])
return []interface{}{transformed}
}
func flattenComputeDiskSourceImageEncryptionKeyRawKey(v interface{}) interface{} {
return v
}
func flattenComputeDiskSourceImageEncryptionKeySha256(v interface{}) interface{} {
return v
}
func flattenComputeDiskSourceImageId(v interface{}) interface{} {
return v
}
func flattenComputeDiskDiskEncryptionKey(v interface{}) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
transformed := make(map[string]interface{})
transformed["raw_key"] =
flattenComputeDiskDiskEncryptionKeyRawKey(original["rawKey"])
transformed["sha256"] =
flattenComputeDiskDiskEncryptionKeySha256(original["sha256"])
return []interface{}{transformed}
}
func flattenComputeDiskDiskEncryptionKeyRawKey(v interface{}) interface{} {
return v
}
func flattenComputeDiskDiskEncryptionKeySha256(v interface{}) interface{} {
return v
}
func flattenComputeDiskSnapshot(v interface{}) interface{} {
if v == nil {
return v
}
return ConvertSelfLinkToV1(v.(string))
}
func flattenComputeDiskSourceSnapshotEncryptionKey(v interface{}) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
transformed := make(map[string]interface{})
transformed["raw_key"] =
flattenComputeDiskSourceSnapshotEncryptionKeyRawKey(original["rawKey"])
transformed["sha256"] =
flattenComputeDiskSourceSnapshotEncryptionKeySha256(original["sha256"])
return []interface{}{transformed}
}
func flattenComputeDiskSourceSnapshotEncryptionKeyRawKey(v interface{}) interface{} {
return v
}
func flattenComputeDiskSourceSnapshotEncryptionKeySha256(v interface{}) interface{} {
return v
}
func flattenComputeDiskSourceSnapshotId(v interface{}) interface{} {
return v
}
func expandComputeDiskDescription(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return v, nil