forked from GoogleCloudPlatform/magic-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_compute_instance_template.go.erb
1563 lines (1411 loc) · 55.5 KB
/
resource_compute_instance_template.go.erb
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
<% autogen_exception -%>
package google
import (
"context"
"fmt"
"reflect"
"strings"
"time"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
<% if version == "ga" -%>
"google.golang.org/api/compute/v1"
<% else -%>
compute "google.golang.org/api/compute/v0.beta"
<% end -%>
)
var (
schedulingInstTemplateKeys = []string{
"scheduling.0.on_host_maintenance",
"scheduling.0.automatic_restart",
"scheduling.0.preemptible",
"scheduling.0.node_affinities",
"scheduling.0.min_node_cpus",
"scheduling.0.provisioning_model",
"scheduling.0.instance_termination_action",
}
shieldedInstanceTemplateConfigKeys = []string{
"shielded_instance_config.0.enable_secure_boot",
"shielded_instance_config.0.enable_vtpm",
"shielded_instance_config.0.enable_integrity_monitoring",
}
)
var REQUIRED_SCRATCH_DISK_SIZE_GB = 375
func resourceComputeInstanceTemplate() *schema.Resource {
return &schema.Resource{
Create: resourceComputeInstanceTemplateCreate,
Read: resourceComputeInstanceTemplateRead,
Delete: resourceComputeInstanceTemplateDelete,
Importer: &schema.ResourceImporter{
State: resourceComputeInstanceTemplateImportState,
},
SchemaVersion: 1,
CustomizeDiff: customdiff.All(
resourceComputeInstanceTemplateSourceImageCustomizeDiff,
resourceComputeInstanceTemplateScratchDiskCustomizeDiff,
resourceComputeInstanceTemplateBootDiskCustomizeDiff,
),
MigrateState: resourceComputeInstanceTemplateMigrateState,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
Delete: schema.DefaultTimeout(4 * time.Minute),
},
// A compute instance template is more or less a subset of a compute
// instance. Please attempt to maintain consistency with the
// resource_compute_instance schema when updating this one.
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: validateGCEName,
Description: `The name of the instance template. If you leave this blank, Terraform will auto-generate a unique name.`,
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `Creates a unique name beginning with the specified prefix. Conflicts with name.`,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
// https://cloud.google.com/compute/docs/reference/latest/instanceTemplates#resource
// uuid is 26 characters, limit the prefix to 37.
value := v.(string)
if len(value) > 37 {
errors = append(errors, fmt.Errorf(
"%q cannot be longer than 37 characters, name is limited to 63", k))
}
return
},
},
"disk": {
Type: schema.TypeList,
Required: true,
ForceNew: true,
Description: `Disks to attach to instances created from this template. This can be specified multiple times for multiple disks.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_delete": {
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
Description: `Whether or not the disk should be auto-deleted. This defaults to true.`,
},
"boot": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
Description: `Indicates that this is a boot disk.`,
},
"device_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `A unique device name that is reflected into the /dev/ tree of a Linux operating system running within the instance. If not specified, the server chooses a default device name to apply to this disk.`,
},
"disk_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Name of the disk. When not provided, this defaults to the name of the instance.`,
},
"disk_size_gb": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The size of the image in gigabytes. If not specified, it will inherit the size of its base image. For SCRATCH disks, the size must be exactly 375GB.`,
},
"disk_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The Google Compute Engine disk type. Such as "pd-ssd", "local-ssd", "pd-balanced" or "pd-standard".`,
},
"labels": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Description: `A set of key/value label pairs to assign to disks,`,
},
"source_image": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
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}. ~> Note: Either source or source_image is required when creating a new instance except for when creating a local SSD.`,
},
"interface": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Description: `Specifies the disk interface to use for attaching this disk.`,
},
"mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The mode in which to attach this disk, either READ_WRITE or READ_ONLY. If you are attaching or creating a boot disk, this must read-write mode.`,
},
"source": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The name (not self_link) of the disk (such as those managed by google_compute_disk) to attach. ~> Note: Either source or source_image is required when creating a new instance except for when creating a local SSD.`,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The type of Google Compute Engine disk, can be either "SCRATCH" or "PERSISTENT".`,
},
"disk_encryption_key": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Description: `Encrypts or decrypts a disk using a customer-supplied encryption key.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"kms_key_self_link": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: compareSelfLinkRelativePaths,
Description: `The self link of the encryption key that is stored in Google Cloud KMS.`,
},
},
},
},
"resource_policies": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Description: `A list (short name or id) of resource policies to attach to this disk. Currently a max of 1 resource policy is supported.`,
Elem: &schema.Schema{
Type: schema.TypeString,
DiffSuppressFunc: compareResourceNames,
},
},
},
},
},
"machine_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The machine type to create. To create a machine with a custom type (such as extended memory), format the value like custom-VCPUS-MEM_IN_MB like custom-6-20480 for 6 vCPU and 20GB of RAM.`,
},
"can_ip_forward": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
Description: `Whether to allow sending and receiving of packets with non-matching source or destination IPs. This defaults to false.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `A brief description of this resource.`,
},
<% unless version == 'ga' -%>
"enable_display": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Description: `Enable Virtual Displays on this instance. Note: allow_stopping_for_update must be set to true in order to update this field.`,
},
<% end -%>
"instance_description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `A description of the instance.`,
},
"metadata": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Description: `Metadata key/value pairs to make available from within instances created from this template.`,
},
"metadata_startup_script": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `An alternative to using the startup-script metadata key, mostly to match the compute_instance resource. This replaces the startup-script metadata key on the created instance and thus the two mechanisms are not allowed to be used simultaneously.`,
},
"metadata_fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: `The unique fingerprint of the metadata.`,
},
<% unless version == 'ga' -%>
"network_performance_config": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Description: `Configures network performance settings for the instance. If not specified, the instance will be created with its default network performance configuration.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"total_egress_bandwidth_tier": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"TIER_1", "DEFAULT"}, false),
Description: `The egress bandwidth tier to enable. Possible values:TIER_1, DEFAULT`,
},
},
},
},
<% end -%>
"network_interface": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `Networks to attach to instances created from this template. This can be specified multiple times for multiple networks.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"network": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
Description: `The name or self_link of the network to attach this interface to. Use network attribute for Legacy or Auto subnetted networks and subnetwork for custom subnetted networks.`,
},
"subnetwork": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
Description: `The name of the subnetwork to attach this interface to. The subnetwork must exist in the same region this instance will be created in. Either network or subnetwork must be provided.`,
},
"subnetwork_project": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The ID of the project in which the subnetwork belongs. If it is not provided, the provider project is used.`,
},
"network_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The private IP address to assign to the instance. If empty, the address will be automatically assigned.`,
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: `The name of the network_interface.`,
},
"nic_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"GVNIC", "VIRTIO_NET"}, false),
Description: `The type of vNIC to be used on this interface. Possible values:GVNIC, VIRTIO_NET`,
},
"access_config": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `Access configurations, i.e. IPs via which this instance can be accessed via the Internet. Omit to ensure that the instance is not accessible from the Internet (this means that ssh provisioners will not work unless you are running Terraform can send traffic to the instance's network (e.g. via tunnel or because it is running on another cloud instance on that network). This block can be repeated multiple times.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"nat_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The IP address that will be 1:1 mapped to the instance's network ip. If not given, one will be generated.`,
},
"network_tier": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The networking tier used for configuring this instance template. This field can take the following values: PREMIUM, STANDARD, FIXED_STANDARD. If this field is not specified, it is assumed to be PREMIUM.`,
},
// Possibly configurable- this was added so we don't break if it's inadvertently set
"public_ptr_domain_name": {
Type: schema.TypeString,
Computed: true,
Description: `The DNS domain name for the public PTR record.The DNS domain name for the public PTR record.`,
},
},
},
},
"alias_ip_range": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `An array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip_cidr_range": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: ipCidrRangeDiffSuppress,
Description: `The IP CIDR range represented by this alias IP range. This IP CIDR range must belong to the specified subnetwork and cannot contain IP addresses reserved by system or used by other network interfaces. At the time of writing only a netmask (e.g. /24) may be supplied, with a CIDR format resulting in an API error.`,
},
"subnetwork_range_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The subnetwork secondary range name specifying the secondary range from which to allocate the IP CIDR range for this alias IP range. If left unspecified, the primary range of the subnetwork will be used.`,
},
},
},
},
"stack_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice([]string{"IPV4_ONLY", "IPV4_IPV6", ""}, false),
Description: `The stack type for this network interface to identify whether the IPv6 feature is enabled or not. If not specified, IPV4_ONLY will be used.`,
},
"ipv6_access_type": {
Type: schema.TypeString,
Computed: true,
Description: `One of EXTERNAL, INTERNAL to indicate whether the IP can be accessed from the Internet. This field is always inherited from its subnetwork.`,
},
"ipv6_access_config": {
Type: schema.TypeList,
Optional: true,
Description: `An array of IPv6 access configurations for this interface. Currently, only one IPv6 access config, DIRECT_IPV6, is supported. If there is no ipv6AccessConfig specified, then this instance will have no external IPv6 Internet access.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"network_tier": {
Type: schema.TypeString,
Required: true,
Description: `The service-level to be provided for IPv6 traffic when the subnet has an external subnet. Only PREMIUM tier is valid for IPv6`,
},
// Possibly configurable- this was added so we don't break if it's inadvertently set
// (assuming the same ass access config)
"public_ptr_domain_name": {
Type: schema.TypeString,
Computed: true,
Description: `The domain name to be used when creating DNSv6 records for the external IPv6 ranges.`,
},
"external_ipv6": {
Type: schema.TypeString,
Computed: true,
Description: `The first IPv6 address of the external IPv6 range associated with this instance, prefix length is stored in externalIpv6PrefixLength in ipv6AccessConfig. The field is output only, an IPv6 address from a subnetwork associated with the instance will be allocated dynamically.`,
},
"external_ipv6_prefix_length": {
Type: schema.TypeString,
Computed: true,
Description: `The prefix length of the external IPv6 range.`,
},
},
},
},
"queue_count": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Description: `The networking queue count that's specified by users for the network interface. Both Rx and Tx queues will be set to this number. It will be empty if not specified.`,
},
},
},
},
"project": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`,
},
"region": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Description: `An instance template is a global resource that is not bound to a zone or a region. However, you can still specify some regional resources in an instance template, which restricts the template to the region where that resource resides. For example, a custom subnetwork resource is tied to a specific region. Defaults to the region of the Provider if no value is given.`,
},
"scheduling": {
Type: schema.TypeList,
Optional: true,
Computed: true,
ForceNew: true,
MaxItems: 1,
Description: `The scheduling strategy to use.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"preemptible": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: schedulingInstTemplateKeys,
Default: false,
ForceNew: true,
Description: `Allows instance to be preempted. This defaults to false.`,
},
"automatic_restart": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: schedulingInstTemplateKeys,
Default: true,
ForceNew: true,
Description: `Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). This defaults to true.`,
},
"on_host_maintenance": {
Type: schema.TypeString,
Optional: true,
Computed: true,
AtLeastOneOf: schedulingInstTemplateKeys,
ForceNew: true,
Description: `Defines the maintenance behavior for this instance.`,
},
"node_affinities": {
Type: schema.TypeSet,
Optional: true,
AtLeastOneOf: schedulingInstTemplateKeys,
ForceNew: true,
Elem: instanceSchedulingNodeAffinitiesElemSchema(),
DiffSuppressFunc: emptyOrDefaultStringSuppress(""),
Description: `Specifies node affinities or anti-affinities to determine which sole-tenant nodes your instances and managed instance groups will use as host systems.`,
},
"min_node_cpus": {
Type: schema.TypeInt,
Optional: true,
AtLeastOneOf: schedulingInstTemplateKeys,
Description: `Minimum number of cpus for the instance.`,
},
"provisioning_model": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
AtLeastOneOf: schedulingInstTemplateKeys,
Description: `Whether the instance is spot. If this is set as SPOT.`,
},
"instance_termination_action": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
AtLeastOneOf: schedulingInstTemplateKeys,
Description: `Specifies the action GCE should take when SPOT VM is preempted.`,
},
},
},
},
"self_link": {
Type: schema.TypeString,
Computed: true,
Description: `The URI of the created resource.`,
},
"service_account": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Description: `Service account to attach to the instance.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"email": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The service account e-mail address. If not given, the default Google Compute Engine service account is used.`,
},
"scopes": {
Type: schema.TypeSet,
Required: true,
ForceNew: true,
Description: `A list of service scopes. Both OAuth2 URLs and gcloud short names are supported. To allow full access to all Cloud APIs, use the cloud-platform scope.`,
Elem: &schema.Schema{
Type: schema.TypeString,
StateFunc: func(v interface{}) string {
return canonicalizeServiceScope(v.(string))
},
},
Set: stringScopeHashcode,
},
},
},
},
"shielded_instance_config": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Description: `Enable Shielded VM on this instance. Shielded VM provides verifiable integrity to prevent against malware and rootkits. Defaults to disabled. Note: shielded_instance_config can only be used with boot images with shielded vm support.`,
// Since this block is used by the API based on which
// image being used, the field needs to be marked as Computed.
Computed: true,
DiffSuppressFunc: emptyOrDefaultStringSuppress(""),
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable_secure_boot": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: shieldedInstanceTemplateConfigKeys,
Default: false,
ForceNew: true,
Description: `Verify the digital signature of all boot components, and halt the boot process if signature verification fails. Defaults to false.`,
},
"enable_vtpm": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: shieldedInstanceTemplateConfigKeys,
Default: true,
ForceNew: true,
Description: `Use a virtualized trusted platform module, which is a specialized computer chip you can use to encrypt objects like keys and certificates. Defaults to true.`,
},
"enable_integrity_monitoring": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: shieldedInstanceTemplateConfigKeys,
Default: true,
ForceNew: true,
Description: `Compare the most recent boot measurements to the integrity policy baseline and return a pair of pass/fail results depending on whether they match or not. Defaults to true.`,
},
},
},
},
"confidential_instance_config": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Computed: true,
Description: `The Confidential VM config being used by the instance. on_host_maintenance has to be set to TERMINATE or this will fail to create.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable_confidential_compute": {
Type: schema.TypeBool,
Required: true,
ForceNew: true,
Description: `Defines whether the instance should have confidential compute enabled.`,
},
},
},
},
"advanced_machine_features": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Description: `Controls for advanced machine-related behavior features.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable_nested_virtualization": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
Description: `Whether to enable nested virtualization or not.`,
},
"threads_per_core": {
Type: schema.TypeInt,
Optional: true,
Computed: false,
ForceNew: true,
Description: `The number of threads per physical core. To disable simultaneous multithreading (SMT) set this to 1. If unset, the maximum number of threads supported per core by the underlying processor is assumed.`,
},
<% unless version == 'ga' -%>
"visible_core_count": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Description: `The number of physical cores to expose to an instance. Multiply by the number of threads per core to compute the total number of virtual CPUs to expose to the instance. If unset, the number of cores is inferred from the instance\'s nominal CPU count and the underlying platform\'s SMT width.`,
},
<% end -%>
},
},
},
"guest_accelerator": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: `List of the type and count of accelerator cards attached to the instance.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"count": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
Description: `The number of the guest accelerator cards exposed to this instance.`,
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
Description: `The accelerator type resource to expose to this instance. E.g. nvidia-tesla-k80.`,
},
},
},
},
"min_cpu_platform": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Specifies a minimum CPU platform. Applicable values are the friendly names of CPU platforms, such as Intel Haswell or Intel Skylake.`,
},
"tags": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Description: `Tags to attach to the instance.`,
},
"tags_fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: `The unique fingerprint of the tags.`,
},
"labels": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Description: `A set of key/value label pairs to assign to instances created from this template,`,
},
"reservation_affinity": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Description: `Specifies the reservations that this instance can consume from.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ANY_RESERVATION", "SPECIFIC_RESERVATION", "NO_RESERVATION"}, false),
Description: `The type of reservation from which this instance can consume resources.`,
},
"specific_reservation": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
Description: `Specifies the label selector for the reservation to use.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Corresponds to the label key of a reservation resource. To target a SPECIFIC_RESERVATION by name, specify compute.googleapis.com/reservation-name as the key and specify the name of your reservation as the only value.`,
},
"values": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
ForceNew: true,
Description: `Corresponds to the label values of a reservation resource.`,
},
},
},
},
},
},
},
},
UseJSONNumber: true,
}
}
func resourceComputeInstanceTemplateSourceImageCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error {
config := meta.(*Config)
numDisks := diff.Get("disk.#").(int)
for i := 0; i < numDisks; i++ {
key := fmt.Sprintf("disk.%d.source_image", i)
if diff.HasChange(key) {
var err error
old, new := diff.GetChange(key)
if old == "" || new == "" {
continue
}
// project must be retrieved once we know there is a diff to resolve, otherwise it will
// attempt to retrieve project during `plan` before all calculated fields are ready
// see https://github.com/hashicorp/terraform-provider-google/issues/2878
project, err := getProjectFromDiff(diff, config)
if err != nil {
return err
}
oldResolved, err := resolveImage(config, project, old.(string), config.userAgent)
if err != nil {
return err
}
oldResolved, err = resolveImageRefToRelativeURI(project, oldResolved)
if err != nil {
return err
}
newResolved, err := resolveImage(config, project, new.(string), config.userAgent)
if err != nil {
return err
}
newResolved, err = resolveImageRefToRelativeURI(project, newResolved)
if err != nil {
return err
}
if oldResolved != newResolved {
continue
}
err = diff.Clear(key)
if err != nil {
return err
}
}
}
return nil
}
func resourceComputeInstanceTemplateScratchDiskCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error {
// separate func to allow unit testing
return resourceComputeInstanceTemplateScratchDiskCustomizeDiffFunc(diff)
}
func resourceComputeInstanceTemplateScratchDiskCustomizeDiffFunc(diff TerraformResourceDiff) error {
numDisks := diff.Get("disk.#").(int)
for i := 0; i < numDisks; i++ {
// misspelled on purpose, type is a special symbol
typee := diff.Get(fmt.Sprintf("disk.%d.type", i)).(string)
diskType := diff.Get(fmt.Sprintf("disk.%d.disk_type", i)).(string)
if typee == "SCRATCH" && diskType != "local-ssd" {
return fmt.Errorf("SCRATCH disks must have a disk_type of local-ssd. disk %d has disk_type %s", i, diskType)
}
if diskType == "local-ssd" && typee != "SCRATCH" {
return fmt.Errorf("disks with a disk_type of local-ssd must be SCRATCH disks. disk %d is a %s disk", i, typee)
}
diskSize := diff.Get(fmt.Sprintf("disk.%d.disk_size_gb", i)).(int)
if typee == "SCRATCH" && diskSize != REQUIRED_SCRATCH_DISK_SIZE_GB {
return fmt.Errorf("SCRATCH disks must be exactly %dGB, disk %d is %d", REQUIRED_SCRATCH_DISK_SIZE_GB, i, diskSize)
}
}
return nil
}
func resourceComputeInstanceTemplateBootDiskCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) error {
numDisks := diff.Get("disk.#").(int)
// No disk except the first can be the boot disk
for i := 1; i < numDisks; i++ {
key := fmt.Sprintf("disk.%d.boot", i)
if v, ok := diff.GetOk(key); ok {
if v.(bool) {
return fmt.Errorf("Only the first disk specified in instance_template can be the boot disk. %s was true", key)
}
}
}
return nil
}
func buildDisks(d *schema.ResourceData, config *Config) ([]*compute.AttachedDisk, error) {
project, err := getProject(d, config)
if err != nil {
return nil, err
}
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return nil, err
}
disksCount := d.Get("disk.#").(int)
disks := make([]*compute.AttachedDisk, 0, disksCount)
for i := 0; i < disksCount; i++ {
prefix := fmt.Sprintf("disk.%d", i)
// Build the disk
var disk compute.AttachedDisk
disk.Type = "PERSISTENT"
disk.Mode = "READ_WRITE"
disk.Interface = "SCSI"
disk.Boot = i == 0
disk.AutoDelete = d.Get(prefix + ".auto_delete").(bool)
if v, ok := d.GetOk(prefix + ".boot"); ok {
disk.Boot = v.(bool)
}
if v, ok := d.GetOk(prefix + ".device_name"); ok {
disk.DeviceName = v.(string)
}
if _, ok := d.GetOk(prefix + ".disk_encryption_key"); ok {
disk.DiskEncryptionKey = &compute.CustomerEncryptionKey{}
if v, ok := d.GetOk(prefix + ".disk_encryption_key.0.kms_key_self_link"); ok {
disk.DiskEncryptionKey.KmsKeyName = v.(string)
}
}
if v, ok := d.GetOk(prefix + ".source"); ok {
disk.Source = v.(string)
conflicts := []string{"disk_size_gb", "disk_name", "disk_type", "source_image", "labels"}
for _, conflict := range conflicts {
if _, ok := d.GetOk(prefix + "." + conflict); ok {
return nil, fmt.Errorf("Cannot use `source` with any of the fields in %s", conflicts)
}
}
} else {
disk.InitializeParams = &compute.AttachedDiskInitializeParams{}
if v, ok := d.GetOk(prefix + ".disk_name"); ok {
disk.InitializeParams.DiskName = v.(string)
}
if v, ok := d.GetOk(prefix + ".disk_size_gb"); ok {
disk.InitializeParams.DiskSizeGb = int64(v.(int))
}
disk.InitializeParams.DiskType = "pd-standard"
if v, ok := d.GetOk(prefix + ".disk_type"); ok {
disk.InitializeParams.DiskType = v.(string)
}
if v, ok := d.GetOk(prefix + ".source_image"); ok {
imageName := v.(string)
imageUrl, err := resolveImage(config, project, imageName, userAgent)
if err != nil {
return nil, fmt.Errorf(
"Error resolving image name '%s': %s",
imageName, err)
}
disk.InitializeParams.SourceImage = imageUrl
}
disk.InitializeParams.Labels = expandStringMap(d, prefix+".labels")
if _, ok := d.GetOk(prefix + ".resource_policies"); ok {
// instance template only supports a resource name here (not uri)
disk.InitializeParams.ResourcePolicies = convertAndMapStringArr(d.Get(prefix+".resource_policies").([]interface{}), GetResourceNameFromSelfLink)
}
}
if v, ok := d.GetOk(prefix + ".interface"); ok {
disk.Interface = v.(string)
}
if v, ok := d.GetOk(prefix + ".mode"); ok {
disk.Mode = v.(string)
}
if v, ok := d.GetOk(prefix + ".type"); ok {
disk.Type = v.(string)
}
disks = append(disks, &disk)
}
return disks, nil
}
// We don't share this code with compute instances because instances want a
// partial URL, but instance templates want the bare accelerator name (despite
// the docs saying otherwise).
//
// Using a partial URL on an instance template results in:
// Invalid value for field 'resource.properties.guestAccelerators[0].acceleratorType':
// 'zones/us-east1-b/acceleratorTypes/nvidia-tesla-k80'.
// Accelerator type 'zones/us-east1-b/acceleratorTypes/nvidia-tesla-k80'
// must be a valid resource name (not an url).
func expandInstanceTemplateGuestAccelerators(d TerraformResourceData, config *Config) []*compute.AcceleratorConfig {
configs, ok := d.GetOk("guest_accelerator")
if !ok {
return nil
}
accels := configs.([]interface{})
guestAccelerators := make([]*compute.AcceleratorConfig, 0, len(accels))
for _, raw := range accels {
data := raw.(map[string]interface{})