forked from hashicorp/terraform-provider-google-beta
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresource_compute_disk.go
2473 lines (2183 loc) · 90.4 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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** Type: MMv1 ***
//
// ----------------------------------------------------------------------------
//
// 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 compute
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"reflect"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"google.golang.org/api/googleapi"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/verify"
)
// diffsuppress for hyperdisk provisioned_iops
func hyperDiskIopsUpdateDiffSuppress(_ context.Context, d *schema.ResourceDiff, meta interface{}) error {
if !strings.Contains(d.Get("type").(string), "hyperdisk") {
resourceSchema := ResourceComputeDisk().Schema
for field := range resourceSchema {
if field == "provisioned_iops" && d.HasChange(field) {
if err := d.ForceNew(field); err != nil {
return err
}
}
}
}
return nil
}
// Suppress all diffs, used for Disk.Interface which is a nonfunctional field
func AlwaysDiffSuppress(_, _, _ string, _ *schema.ResourceData) bool {
return true
}
// diffsuppress for beta and to check change in source_disk attribute
func sourceDiskDiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
s1 := strings.TrimPrefix(old, "https://www.googleapis.com/compute/beta")
s2 := strings.TrimPrefix(new, "https://www.googleapis.com/compute/v1")
if strings.HasSuffix(s1, s2) {
return true
}
return false
}
// Is the new disk size smaller than the old one?
func IsDiskShrinkage(_ context.Context, 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-11-bullseye-v20220719, family name: debian-11
// First condition is to check if image contains arm64 because of case like:
// image name: opensuse-leap-15-4-v20220713-arm64, family name: opensuse-leap (should not be evaluated during handling of amd64 cases)
// In second condition, we have to check for amd64 because of cases like:
// image name: ubuntu-2210-kinetic-amd64-v20221022, family name: ubuntu-2210 (should not suppress)
if !strings.Contains(imageName, "-arm64") && strings.Contains(imageName, strings.TrimSuffix(familyName, "-amd64")) {
if strings.Contains(imageName, "-amd64") {
return strings.HasSuffix(familyName, "-amd64")
} else {
return !strings.HasSuffix(familyName, "-amd64")
}
}
// We have to check for arm64 because of cases like:
// image name: opensuse-leap-15-4-v20220713-arm64, family name: opensuse-leap (should not suppress)
if strings.Contains(imageName, strings.TrimSuffix(familyName, "-arm64")) {
if strings.Contains(imageName, "-arm64") {
return strings.HasSuffix(familyName, "-arm64")
} else {
return !strings.HasSuffix(familyName, "-arm64")
}
}
if suppressCanonicalFamilyDiff(imageName, familyName) {
return true
}
if suppressCosFamilyDiff(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) == 4 {
var f string
if parts[3] == "" {
f = fmt.Sprintf("ubuntu-%s%s-lts", parts[1], parts[2])
} else {
f = fmt.Sprintf("ubuntu-%s%s-lts-%s", parts[1], parts[2], parts[3])
}
if f == familyName {
return true
}
}
return false
}
// e.g. image: cos-NN-*, family: cos-NN-lts
func suppressCosFamilyDiff(imageName, familyName string) bool {
parts := cosLtsImage.FindStringSubmatch(imageName)
if len(parts) == 2 {
f := fmt.Sprintf("cos-%s-lts", parts[1])
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)
updatedImageName := strings.Replace(imageName, "-dc-", "-", 1)
return strings.Contains(updatedImageName, updatedFamilyString)
}
// ExpandStoragePoolUrl returns a full self link from a partial self link.
func ExpandStoragePoolUrl(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (string, error) {
// It does not try to construct anything from empty.
if v == nil || v.(string) == "" {
return "", nil
}
project, err := tpgresource.GetProject(d, config)
if err != nil {
return "", err
}
zone, err := tpgresource.GetZone(d, config)
if err != nil {
return "", err
}
formattedStr := v.(string)
if strings.HasPrefix(v.(string), "/") {
formattedStr = formattedStr[1:]
}
replacedStr := ""
if strings.HasPrefix(formattedStr, "https://") {
// Anything that starts with a URL scheme is assumed to be a self link worth using.
return formattedStr, nil
} else if strings.HasPrefix(formattedStr, "projects/") {
// If the self link references a project, we'll just stuck the compute prefix on it
replacedStr = config.ComputeBasePath + formattedStr
} else if strings.HasPrefix(formattedStr, "zones/") {
// For regional or zonal resources which include their region or zone, just put the project in front.
replacedStr = config.ComputeBasePath + "projects/" + project + "/" + formattedStr
} else {
// Anything else is assumed to be a zonal resource, with a partial link that begins with the resource name.
replacedStr = config.ComputeBasePath + "projects/" + project + "/zones/" + zone + "/storagePools/" + formattedStr
}
return replacedStr, nil
}
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(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
CustomizeDiff: customdiff.All(
customdiff.ForceNewIfChange("size", IsDiskShrinkage),
hyperDiskIopsUpdateDiffSuppress,
tpgresource.SetLabelsDiff,
tpgresource.DefaultProviderProject,
),
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: verify.ValidateGCEName,
Description: `Name of the resource. Provided by the client when the resource is
created. The name must be 1-63 characters long, and comply with
RFC1035. Specifically, the name must be 1-63 characters long and match
the regular expression '[a-z]([-a-z0-9]*[a-z0-9])?' which means the
first character must be a lowercase letter, and all following
characters must be a dash, lowercase letter, or digit, except the last
character, which cannot be a dash.`,
},
"access_mode": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `The accessMode of the disk.
For example:
* READ_WRITE_SINGLE
* READ_WRITE_MANY
* READ_ONLY_SINGLE`,
},
"async_primary_disk": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareSelfLinkRelativePaths,
Description: `A nested object resource.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"disk": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Primary disk for asynchronous disk replication.`,
},
},
},
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `An optional description of this resource. Provide this property when
you create the resource.`,
},
"disk_encryption_key": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `Encrypts the disk using a customer-supplied encryption key.
After you encrypt a disk with a customer-supplied key, you must
provide the same key if you use the disk later (e.g. to create a disk
snapshot or an image, or to attach the disk to a virtual machine).
Customer-supplied encryption keys do not protect access to metadata of
the disk.
If you do not provide an encryption key when creating the disk, then
the disk will be encrypted using an automatically generated key and
you do not need to provide a key to use the disk later.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"kms_key_self_link": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareSelfLinkRelativePaths,
Description: `The self link of the encryption key used to encrypt the disk. Also called KmsKeyName
in the cloud console. Your project's Compute Engine System service account
('service-{{PROJECT_NUMBER}}@compute-system.iam.gserviceaccount.com') must have
'roles/cloudkms.cryptoKeyEncrypterDecrypter' to use this feature.
See https://cloud.google.com/compute/docs/disks/customer-managed-encryption#encrypt_a_new_persistent_disk_with_your_own_keys`,
},
"kms_key_service_account": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The service account used for the encryption request for the given KMS key.
If absent, the Compute Engine Service Agent service account is used.`,
},
"raw_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Specifies a 256-bit customer-supplied encryption key, encoded in
RFC 4648 base64 to either encrypt or decrypt this resource.`,
Sensitive: true,
},
"rsa_encrypted_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Specifies an RFC 4648 base64 encoded, RSA-wrapped 2048-bit
customer-supplied encryption key to either encrypt or decrypt
this resource. You can provide either the rawKey or the rsaEncryptedKey.`,
Sensitive: true,
},
"sha256": {
Type: schema.TypeString,
Computed: true,
Description: `The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied
encryption key that protects this resource.`,
},
},
},
},
"enable_confidential_compute": {
Type: schema.TypeBool,
Computed: true,
Optional: true,
ForceNew: true,
Description: `Whether this disk is using confidential compute mode.
Note: Only supported on hyperdisk skus, disk_encryption_key is required when setting to true`,
},
"guest_os_features": {
Type: schema.TypeSet,
Computed: true,
Optional: true,
ForceNew: true,
Description: `A list of features to enable on the guest operating system.
Applicable only for bootable disks.`,
Elem: computeDiskGuestOsFeaturesSchema(),
// Default schema.HashSchema is used.
},
"image": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: DiskImageDiffSuppress,
Description: `The image from which to initialize this disk. This can be
one of: the image's 'self_link', 'projects/{project}/global/images/{image}',
'projects/{project}/global/images/family/{family}', 'global/images/{image}',
'global/images/family/{family}', 'family/{family}', '{project}/{family}',
'{project}/{image}', '{family}', or '{image}'. If referred by family, the
images names must include the family name. If they don't, use the
[google_compute_image data source](/docs/providers/google/d/compute_image.html).
For instance, the image 'centos-6-v20180104' includes its family name 'centos-6'.
These images can be referred by family name here.`,
},
"interface": {
Type: schema.TypeString,
Optional: true,
Deprecated: "`interface` is deprecated and will be removed in a future major release. This field is no longer used and can be safely removed from your configurations; disk interfaces are automatically determined on attachment.",
ForceNew: true,
DiffSuppressFunc: AlwaysDiffSuppress,
Description: `Specifies the disk interface to use for attaching this disk, which is either SCSI or NVME. The default is SCSI.`,
Default: "SCSI",
},
"labels": {
Type: schema.TypeMap,
Optional: true,
Description: `Labels to apply to this disk. A list of key->value pairs.
**Note**: This field is non-authoritative, and will only manage the labels present in your configuration.
Please refer to the field 'effective_labels' for all of the labels present on the resource.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"licenses": {
Type: schema.TypeList,
Computed: true,
Optional: true,
ForceNew: true,
Description: `Any applicable license URI.`,
Elem: &schema.Schema{
Type: schema.TypeString,
DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName,
},
},
"multi_writer": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Description: `Indicates whether or not the disk can be read/write attached to more than one instance.`,
},
"physical_block_size_bytes": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
ForceNew: true,
Description: `Physical block size of the persistent disk, in bytes. If not present
in a request, a default value is used. Currently supported sizes
are 4096 and 16384, other sizes may be added in the future.
If an unsupported value is requested, the error message will list
the supported values for the caller's project.`,
},
"provisioned_iops": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
Description: `Indicates how many IOPS must be provisioned for the disk.
Note: Updating currently is only supported by hyperdisk skus without the need to delete and recreate the disk, hyperdisk
allows for an update of IOPS every 4 hours. To update your hyperdisk more frequently, you'll need to manually delete and recreate it`,
},
"provisioned_throughput": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
Description: `Indicates how much Throughput must be provisioned for the disk.
Note: Updating currently is only supported by hyperdisk skus without the need to delete and recreate the disk, hyperdisk
allows for an update of Throughput every 4 hours. To update your hyperdisk more frequently, you'll need to manually delete and recreate it`,
},
"resource_policies": {
Type: schema.TypeList,
Computed: true,
Optional: true,
ForceNew: true,
Description: `Resource policies applied to this disk for automatic snapshot creations.
~>**NOTE** This value does not support updating the
resource policy, as resource policies can not be updated more than
one at a time. Use
['google_compute_disk_resource_policy_attachment'](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_disk_resource_policy_attachment)
to allow for updating the resource policy attached to the disk.`,
Elem: &schema.Schema{
Type: schema.TypeString,
DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName,
},
},
"size": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
Description: `Size of the persistent disk, specified in GB. You can specify this
field when creating a persistent disk using the 'image' or
'snapshot' parameter, or specify it alone to create an empty
persistent disk.
If you specify this field along with 'image' or 'snapshot',
the value must not be less than the size of the image
or the size of the snapshot.
~>**NOTE** If you change the size, Terraform updates the disk size
if upsizing is detected but recreates the disk if downsizing is requested.
You can add 'lifecycle.prevent_destroy' in the config to prevent destroying
and recreating.`,
},
"snapshot": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName,
Description: `The source snapshot used to create this disk. You can provide this as
a partial or full URL to the resource. If the snapshot is in another
project than this disk, you must supply a full URL. For example, the
following are valid values:
* 'https://www.googleapis.com/compute/v1/projects/project/global/snapshots/snapshot'
* 'projects/project/global/snapshots/snapshot'
* 'global/snapshots/snapshot'
* 'snapshot'`,
},
"source_disk": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: sourceDiskDiffSuppress,
Description: `The source disk used to create this disk. You can provide this as a partial or full URL to the resource.
For example, the following are valid values:
* https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks/{disk}
* https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/disks/{disk}
* projects/{project}/zones/{zone}/disks/{disk}
* projects/{project}/regions/{region}/disks/{disk}
* zones/{zone}/disks/{disk}
* regions/{region}/disks/{disk}`,
},
"source_image_encryption_key": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `The customer-supplied encryption key of the source image. Required if
the source image is protected by a customer-supplied encryption key.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"kms_key_self_link": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareSelfLinkRelativePaths,
Description: `The self link of the encryption key used to encrypt the disk. Also called KmsKeyName
in the cloud console. Your project's Compute Engine System service account
('service-{{PROJECT_NUMBER}}@compute-system.iam.gserviceaccount.com') must have
'roles/cloudkms.cryptoKeyEncrypterDecrypter' to use this feature.
See https://cloud.google.com/compute/docs/disks/customer-managed-encryption#encrypt_a_new_persistent_disk_with_your_own_keys`,
},
"kms_key_service_account": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The service account used for the encryption request for the given KMS key.
If absent, the Compute Engine Service Agent service account is used.`,
},
"raw_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Specifies a 256-bit customer-supplied encryption key, encoded in
RFC 4648 base64 to either encrypt or decrypt this resource.`,
},
"sha256": {
Type: schema.TypeString,
Computed: true,
Description: `The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied
encryption key that protects this resource.`,
},
},
},
},
"source_snapshot_encryption_key": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `The customer-supplied encryption key of the source snapshot. Required
if the source snapshot is protected by a customer-supplied encryption
key.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"kms_key_self_link": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareSelfLinkRelativePaths,
Description: `The self link of the encryption key used to encrypt the disk. Also called KmsKeyName
in the cloud console. Your project's Compute Engine System service account
('service-{{PROJECT_NUMBER}}@compute-system.iam.gserviceaccount.com') must have
'roles/cloudkms.cryptoKeyEncrypterDecrypter' to use this feature.
See https://cloud.google.com/compute/docs/disks/customer-managed-encryption#encrypt_a_new_persistent_disk_with_your_own_keys`,
},
"kms_key_service_account": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The service account used for the encryption request for the given KMS key.
If absent, the Compute Engine Service Agent service account is used.`,
},
"raw_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Specifies a 256-bit customer-supplied encryption key, encoded in
RFC 4648 base64 to either encrypt or decrypt this resource.`,
},
"sha256": {
Type: schema.TypeString,
Computed: true,
Description: `The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied
encryption key that protects this resource.`,
},
},
},
},
"storage_pool": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareResourceNames,
Description: `The URL or the name of the storage pool in which the new disk is created.
For example:
* https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/storagePools/{storagePool}
* /projects/{project}/zones/{zone}/storagePools/{storagePool}
* /zones/{zone}/storagePools/{storagePool}
* /{storagePool}`,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareResourceNames,
Description: `URL of the disk type resource describing which disk type to use to
create the disk. Provide this when creating the disk.`,
Default: "pd-standard",
},
"zone": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName,
Description: `A reference to the zone where the disk resides.`,
},
"disk_id": {
Type: schema.TypeString,
Computed: true,
Description: `The unique identifier for the resource. This identifier is defined by the server.`,
},
"creation_timestamp": {
Type: schema.TypeString,
Computed: true,
Description: `Creation timestamp in RFC3339 text format.`,
},
"effective_labels": {
Type: schema.TypeMap,
Computed: true,
Description: `All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"label_fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: `The fingerprint used for optimistic locking of this resource. Used
internally during updates.`,
},
"last_attach_timestamp": {
Type: schema.TypeString,
Computed: true,
Description: `Last attach timestamp in RFC3339 text format.`,
},
"last_detach_timestamp": {
Type: schema.TypeString,
Computed: true,
Description: `Last detach timestamp in RFC3339 text format.`,
},
"source_disk_id": {
Type: schema.TypeString,
Computed: true,
Description: `The ID value of the disk used to create this image. This value may
be used to determine whether the image was taken from the current
or a previous instance of a given disk name.`,
},
"source_image_id": {
Type: schema.TypeString,
Computed: true,
Description: `The ID value of the image used to create this disk. This value
identifies the exact image that was used to create this persistent
disk. For example, if you created the persistent disk from an image
that was later deleted and recreated under the same name, the source
image ID would identify the exact version of the image that was used.`,
},
"source_snapshot_id": {
Type: schema.TypeString,
Computed: true,
Description: `The unique ID of the snapshot used to create this disk. This value
identifies the exact snapshot that was used to create this persistent
disk. For example, if you created the persistent disk from a snapshot
that was later deleted and recreated under the same name, the source
snapshot ID would identify the exact version of the snapshot that was
used.`,
},
"terraform_labels": {
Type: schema.TypeMap,
Computed: true,
Description: `The combination of labels configured directly on the resource
and default labels configured on the provider.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"users": {
Type: schema.TypeList,
Computed: true,
Description: `Links to the users of the disk (attached instances) in form:
project/zones/zone/instances/instance`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"self_link": {
Type: schema.TypeString,
Computed: true,
},
},
UseJSONNumber: true,
}
}
func computeDiskGuestOsFeaturesSchema() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The type of supported feature. Read [Enabling guest operating system features](https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#guest-os-features) to see a list of available options.`,
},
},
}
}
func resourceComputeDiskCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
obj := make(map[string]interface{})
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"); !tpgresource.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"); !tpgresource.IsEmptyValue(reflect.ValueOf(diskEncryptionKeyProp)) && (ok || !reflect.DeepEqual(v, diskEncryptionKeyProp)) {
obj["diskEncryptionKey"] = diskEncryptionKeyProp
}
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"); !tpgresource.IsEmptyValue(reflect.ValueOf(sourceSnapshotEncryptionKeyProp)) && (ok || !reflect.DeepEqual(v, sourceSnapshotEncryptionKeyProp)) {
obj["sourceSnapshotEncryptionKey"] = sourceSnapshotEncryptionKeyProp
}
labelFingerprintProp, err := expandComputeDiskLabelFingerprint(d.Get("label_fingerprint"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("label_fingerprint"); !tpgresource.IsEmptyValue(reflect.ValueOf(labelFingerprintProp)) && (ok || !reflect.DeepEqual(v, labelFingerprintProp)) {
obj["labelFingerprint"] = labelFingerprintProp
}
descriptionProp, err := expandComputeDiskDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
nameProp, err := expandComputeDiskName(d.Get("name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("name"); !tpgresource.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"); !tpgresource.IsEmptyValue(reflect.ValueOf(sizeGbProp)) && (ok || !reflect.DeepEqual(v, sizeGbProp)) {
obj["sizeGb"] = sizeGbProp
}
physicalBlockSizeBytesProp, err := expandComputeDiskPhysicalBlockSizeBytes(d.Get("physical_block_size_bytes"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("physical_block_size_bytes"); !tpgresource.IsEmptyValue(reflect.ValueOf(physicalBlockSizeBytesProp)) && (ok || !reflect.DeepEqual(v, physicalBlockSizeBytesProp)) {
obj["physicalBlockSizeBytes"] = physicalBlockSizeBytesProp
}
sourceDiskProp, err := expandComputeDiskSourceDisk(d.Get("source_disk"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("source_disk"); !tpgresource.IsEmptyValue(reflect.ValueOf(sourceDiskProp)) && (ok || !reflect.DeepEqual(v, sourceDiskProp)) {
obj["sourceDisk"] = sourceDiskProp
}
typeProp, err := expandComputeDiskType(d.Get("type"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("type"); !tpgresource.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"); !tpgresource.IsEmptyValue(reflect.ValueOf(sourceImageProp)) && (ok || !reflect.DeepEqual(v, sourceImageProp)) {
obj["sourceImage"] = sourceImageProp
}
resourcePoliciesProp, err := expandComputeDiskResourcePolicies(d.Get("resource_policies"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("resource_policies"); !tpgresource.IsEmptyValue(reflect.ValueOf(resourcePoliciesProp)) && (ok || !reflect.DeepEqual(v, resourcePoliciesProp)) {
obj["resourcePolicies"] = resourcePoliciesProp
}
enableConfidentialComputeProp, err := expandComputeDiskEnableConfidentialCompute(d.Get("enable_confidential_compute"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("enable_confidential_compute"); !tpgresource.IsEmptyValue(reflect.ValueOf(enableConfidentialComputeProp)) && (ok || !reflect.DeepEqual(v, enableConfidentialComputeProp)) {
obj["enableConfidentialCompute"] = enableConfidentialComputeProp
}
multiWriterProp, err := expandComputeDiskMultiWriter(d.Get("multi_writer"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("multi_writer"); !tpgresource.IsEmptyValue(reflect.ValueOf(multiWriterProp)) && (ok || !reflect.DeepEqual(v, multiWriterProp)) {
obj["multiWriter"] = multiWriterProp
}
provisionedIopsProp, err := expandComputeDiskProvisionedIops(d.Get("provisioned_iops"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("provisioned_iops"); !tpgresource.IsEmptyValue(reflect.ValueOf(provisionedIopsProp)) && (ok || !reflect.DeepEqual(v, provisionedIopsProp)) {
obj["provisionedIops"] = provisionedIopsProp
}
provisionedThroughputProp, err := expandComputeDiskProvisionedThroughput(d.Get("provisioned_throughput"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("provisioned_throughput"); !tpgresource.IsEmptyValue(reflect.ValueOf(provisionedThroughputProp)) && (ok || !reflect.DeepEqual(v, provisionedThroughputProp)) {
obj["provisionedThroughput"] = provisionedThroughputProp
}
asyncPrimaryDiskProp, err := expandComputeDiskAsyncPrimaryDisk(d.Get("async_primary_disk"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("async_primary_disk"); !tpgresource.IsEmptyValue(reflect.ValueOf(asyncPrimaryDiskProp)) && (ok || !reflect.DeepEqual(v, asyncPrimaryDiskProp)) {
obj["asyncPrimaryDisk"] = asyncPrimaryDiskProp
}
guestOsFeaturesProp, err := expandComputeDiskGuestOsFeatures(d.Get("guest_os_features"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("guest_os_features"); !tpgresource.IsEmptyValue(reflect.ValueOf(guestOsFeaturesProp)) && (ok || !reflect.DeepEqual(v, guestOsFeaturesProp)) {
obj["guestOsFeatures"] = guestOsFeaturesProp
}
licensesProp, err := expandComputeDiskLicenses(d.Get("licenses"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("licenses"); !tpgresource.IsEmptyValue(reflect.ValueOf(licensesProp)) && (ok || !reflect.DeepEqual(v, licensesProp)) {
obj["licenses"] = licensesProp
}
storagePoolProp, err := expandComputeDiskStoragePool(d.Get("storage_pool"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("storage_pool"); !tpgresource.IsEmptyValue(reflect.ValueOf(storagePoolProp)) && (ok || !reflect.DeepEqual(v, storagePoolProp)) {
obj["storagePool"] = storagePoolProp
}
accessModeProp, err := expandComputeDiskAccessMode(d.Get("access_mode"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("access_mode"); !tpgresource.IsEmptyValue(reflect.ValueOf(accessModeProp)) && (ok || !reflect.DeepEqual(v, accessModeProp)) {
obj["accessMode"] = accessModeProp
}
labelsProp, err := expandComputeDiskEffectiveLabels(d.Get("effective_labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
zoneProp, err := expandComputeDiskZone(d.Get("zone"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("zone"); !tpgresource.IsEmptyValue(reflect.ValueOf(zoneProp)) && (ok || !reflect.DeepEqual(v, zoneProp)) {
obj["zone"] = zoneProp
}