forked from hashicorp/terraform-provider-vsphere
/
resource_vsphere_virtual_machine.go
1413 lines (1295 loc) · 53.1 KB
/
resource_vsphere_virtual_machine.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
package vsphere
import (
"errors"
"fmt"
"log"
"strings"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/customattribute"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/datastore"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/folder"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/hostsystem"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/resourcepool"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/storagepod"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/structure"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/vappcontainer"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/viapi"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/virtualmachine"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/virtualdevice"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/vmworkflow"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
// formatVirtualMachinePostCloneRollbackError defines the verbose error when
// rollback fails on a post-clone virtual machine operation.
const formatVirtualMachinePostCloneRollbackError = `
WARNING:
There was an error performing post-clone changes to virtual machine %q:
%s
Additionally, there was an error removing the cloned virtual machine:
%s
The virtual machine may still exist in Terraform state. If it does, the
resource will need to be tainted before trying again. For more information on
how to do this, see the following page:
https://www.terraform.io/docs/commands/taint.html
If the virtual machine does not exist in state, manually delete it to try again.
`
// formatVirtualMachineCustomizationWaitError defines the verbose error that is
// sent when the customization waiter returns an error. This can either be due
// to timeout waiting for respective events or a guest-specific customization
// error. The resource does not roll back in this case, to assist with
// troubleshooting.
const formatVirtualMachineCustomizationWaitError = `
Virtual machine customization failed on %q:
%s
The virtual machine has not been deleted to assist with troubleshooting. If
corrective steps are taken without modifying the "customize" block of the
resource configuration, the resource will need to be tainted before trying
again. For more information on how to do this, see the following page:
https://www.terraform.io/docs/commands/taint.html
`
func resourceVSphereVirtualMachine() *schema.Resource {
s := map[string]*schema.Schema{
"resource_pool_id": {
Type: schema.TypeString,
Required: true,
Description: "The ID of a resource pool to put the virtual machine in.",
},
"datastore_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"datastore_cluster_id"},
Description: "The ID of the virtual machine's datastore. The virtual machine configuration is placed here, along with any virtual disks that are created without datastores.",
},
"datastore_cluster_id": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"datastore_id"},
Description: "The ID of a datastore cluster to put the virtual machine in.",
},
"folder": {
Type: schema.TypeString,
Optional: true,
Description: "The name of the folder to locate the virtual machine in.",
StateFunc: folder.NormalizePath,
},
"host_system_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The ID of an optional host system to pin the virtual machine to.",
},
"wait_for_guest_net_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 5,
Description: "The amount of time, in minutes, to wait for an available IP address on this virtual machine. A value less than 1 disables the waiter.",
},
"wait_for_guest_net_routable": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Controls whether or not the guest network waiter waits for a routable address. When false, the waiter does not wait for a default gateway, nor are IP addresses checked against any discovered default gateways as part of its success criteria.",
},
"shutdown_wait_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 3,
Description: "The amount of time, in minutes, to wait for shutdown when making necessary updates to the virtual machine.",
ValidateFunc: validation.IntBetween(1, 10),
},
"migrate_wait_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
Description: "The amount of time, in minutes, to wait for a vMotion operation to complete before failing.",
ValidateFunc: validation.IntAtLeast(10),
},
"force_power_off": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Set to true to force power-off a virtual machine if a graceful guest shutdown failed for a necessary operation.",
},
"scsi_controller_count": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
Description: "The number of SCSI controllers that Terraform manages on this virtual machine. This directly affects the amount of disks you can add to the virtual machine and the maximum disk unit number. Note that lowering this value does not remove controllers.",
ValidateFunc: validation.IntBetween(1, 4),
},
"scsi_type": {
Type: schema.TypeString,
Optional: true,
Default: virtualdevice.SubresourceControllerTypeParaVirtual,
Description: "The type of SCSI bus this virtual machine will have. Can be one of lsilogic, lsilogic-sas or pvscsi.",
ValidateFunc: validation.StringInSlice(virtualdevice.SCSIBusTypeAllowedValues, false),
},
"scsi_bus_sharing": {
Type: schema.TypeString,
Optional: true,
Default: string(types.VirtualSCSISharingNoSharing),
Description: "Mode for sharing the SCSI bus. The modes are physicalSharing, virtualSharing, and noSharing.",
ValidateFunc: validation.StringInSlice(virtualdevice.SCSIBusSharingAllowedValues, false),
},
// NOTE: disk is only optional so that we can flag it as computed and use
// it in ResourceDiff. We validate this field in ResourceDiff to enforce it
// having a minimum count of 1 for now - but may support diskless VMs
// later.
"disk": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Description: "A specification for a virtual disk device on this virtual machine.",
MaxItems: 60,
Elem: &schema.Resource{Schema: virtualdevice.DiskSubresourceSchema()},
},
"network_interface": {
Type: schema.TypeList,
Required: true,
Description: "A specification for a virtual NIC on this virtual machine.",
MaxItems: 10,
Elem: &schema.Resource{Schema: virtualdevice.NetworkInterfaceSubresourceSchema()},
},
"cdrom": {
Type: schema.TypeList,
Optional: true,
Description: "A specification for a CDROM device on this virtual machine.",
MaxItems: 1,
Elem: &schema.Resource{Schema: virtualdevice.CdromSubresourceSchema()},
},
"clone": {
Type: schema.TypeList,
Optional: true,
Description: "A specification for cloning a virtual machine from template.",
MaxItems: 1,
Elem: &schema.Resource{Schema: vmworkflow.VirtualMachineCloneSchema()},
},
"reboot_required": {
Type: schema.TypeBool,
Computed: true,
Description: "Value internal to Terraform used to determine if a configuration set change requires a reboot.",
},
"vmware_tools_status": {
Type: schema.TypeString,
Computed: true,
Description: "The state of VMware tools in the guest. This will determine the proper course of action for some device operations.",
},
"vmx_path": {
Type: schema.TypeString,
Computed: true,
Description: "The path of the virtual machine's configuration file in the VM's datastore.",
},
"imported": {
Type: schema.TypeBool,
Computed: true,
Description: "A flag internal to Terraform that indicates that this resource was either imported or came from a earlier major version of this resource. Reset after the first post-import or post-upgrade apply.",
},
"moid": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "The machine object ID from VMWare",
},
vSphereTagAttributeKey: tagsSchema(),
customattribute.ConfigKey: customattribute.ConfigSchema(),
}
structure.MergeSchema(s, schemaVirtualMachineConfigSpec())
structure.MergeSchema(s, schemaVirtualMachineGuestInfo())
return &schema.Resource{
Create: resourceVSphereVirtualMachineCreate,
Read: resourceVSphereVirtualMachineRead,
Update: resourceVSphereVirtualMachineUpdate,
Delete: resourceVSphereVirtualMachineDelete,
CustomizeDiff: resourceVSphereVirtualMachineCustomizeDiff,
Importer: &schema.ResourceImporter{
State: resourceVSphereVirtualMachineImport,
},
SchemaVersion: 3,
MigrateState: resourceVSphereVirtualMachineMigrateState,
Schema: s,
}
}
func resourceVSphereVirtualMachineCreate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] %s: Beginning create", resourceVSphereVirtualMachineIDString(d))
client := meta.(*VSphereClient).vimClient
tagsClient, err := tagsClientIfDefined(d, meta)
if err != nil {
return err
}
// Verify a proper vCenter before proceeding if custom attributes are defined
attrsProcessor, err := customattribute.GetDiffProcessorIfAttributesDefined(client, d)
if err != nil {
return err
}
var vm *object.VirtualMachine
// This is where we process our various VM deploy workflows. We expect the ID
// of the resource to be set in the workflow to ensure that any post-create
// operations that fail during this process don't create a dangling resource.
// The VM should also be returned powered on.
switch {
case len(d.Get("clone").([]interface{})) > 0:
vm, err = resourceVSphereVirtualMachineCreateClone(d, meta)
default:
vm, err = resourceVSphereVirtualMachineCreateBare(d, meta)
}
if err != nil {
return err
}
// Tag the VM
if tagsClient != nil {
if err := processTagDiff(tagsClient, d, vm); err != nil {
return err
}
}
// Set custom attributes
if attrsProcessor != nil {
if err := attrsProcessor.ProcessDiff(vm); err != nil {
return err
}
}
// The host attribute of CreateVM_Task seems to be ignored in vCenter 6.7.
// Ensure that VMs are on the correct host and relocate if necessary. Do this
// near the end of the VM creation since it involves updating the
// ResourceData.
vprops, err := virtualmachine.Properties(vm)
if err != nil {
return err
}
if hid, ok := d.GetOk("host_system_id"); hid.(string) != vprops.Runtime.Host.Reference().Value && ok {
err = resourceVSphereVirtualMachineRead(d, meta)
if err != nil {
return err
}
// Restore the old host_system_id so we can still tell if a relocation is
// necessary.
err = d.Set("host_system_id", hid.(string))
if err != nil {
return err
}
if err = resourceVSphereVirtualMachineUpdateLocation(d, meta); err != nil {
return err
}
}
// Wait for a routable address if we have been set to wait for one
err = virtualmachine.WaitForGuestNet(
client,
vm,
d.Get("wait_for_guest_net_routable").(bool),
d.Get("wait_for_guest_net_timeout").(int),
)
if err != nil {
return err
}
// All done!
log.Printf("[DEBUG] %s: Create complete", resourceVSphereVirtualMachineIDString(d))
return resourceVSphereVirtualMachineRead(d, meta)
}
func resourceVSphereVirtualMachineRead(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] %s: Reading state of virtual machine", resourceVSphereVirtualMachineIDString(d))
client := meta.(*VSphereClient).vimClient
id := d.Id()
vm, err := virtualmachine.FromUUID(client, id)
if err != nil {
if _, ok := err.(*virtualmachine.UUIDNotFoundError); ok {
log.Printf("[DEBUG] %s: Virtual machine not found, marking resource as gone: %s", resourceVSphereVirtualMachineIDString(d), err)
d.SetId("")
return nil
}
return fmt.Errorf("error searching for with UUID %q: %s", id, err)
}
vprops, err := virtualmachine.Properties(vm)
if err != nil {
return fmt.Errorf("error fetching VM properties: %s", err)
}
// Set the managed object id.
moid := vm.Reference().Value
d.Set("moid", moid)
log.Printf("[DEBUG] MOID for VM %q is %q", vm.InventoryPath, moid)
// Reset reboot_required. This is an update only variable and should not be
// set across TF runs.
d.Set("reboot_required", false)
// Check to see if VMware tools is running.
if vprops.Guest != nil {
d.Set("vmware_tools_status", vprops.Guest.ToolsRunningStatus)
}
// Resource pool
if vprops.ResourcePool != nil {
d.Set("resource_pool_id", vprops.ResourcePool.Value)
}
// If the VM is part of a vApp, InventoryPath will point to a host path
// rather than a VM path, so this step must be skipped.
if !vappcontainer.IsVApp(client, vprops.ResourcePool.Value) {
f, err := folder.RootPathParticleVM.SplitRelativeFolder(vm.InventoryPath)
if err != nil {
return fmt.Errorf("error parsing virtual machine path %q: %s", vm.InventoryPath, err)
}
d.Set("folder", folder.NormalizePath(f))
}
// Set VM's current host ID if available
if vprops.Runtime.Host != nil {
d.Set("host_system_id", vprops.Runtime.Host.Value)
}
// Set the VMX path and default datastore
dp := &object.DatastorePath{}
if ok := dp.FromString(vprops.Config.Files.VmPathName); !ok {
return fmt.Errorf("could not parse VMX file path: %s", vprops.Config.Files.VmPathName)
}
// The easiest path for us to get an exact match on the datastore in use is
// to look for the datastore name in the list of used datastores. This is
// something we have access to from the VM's properties. This allows us to
// get away with not having to have the datastore unnecessarily supplied to
// the resource when it's not used by anything else.
var ds *object.Datastore
for _, dsRef := range vprops.Datastore {
dsx, err := datastore.FromID(client, dsRef.Value)
if err != nil {
return fmt.Errorf("error locating VMX datastore: %s", err)
}
dsxProps, err := datastore.Properties(dsx)
if err != nil {
return fmt.Errorf("error fetching VMX datastore properties: %s", err)
}
if dsxProps.Summary.Name == dp.Datastore {
ds = dsx
}
}
if ds == nil {
return fmt.Errorf("VMX datastore %s not found", dp.Datastore)
}
d.Set("datastore_id", ds.Reference().Value)
d.Set("vmx_path", dp.Path)
// Read general VM config info
if err := flattenVirtualMachineConfigInfo(d, vprops.Config); err != nil {
return fmt.Errorf("error reading virtual machine configuration: %s", err)
}
// Perform pending device read operations.
devices := object.VirtualDeviceList(vprops.Config.Hardware.Device)
// Read the state of the SCSI bus.
d.Set("scsi_type", virtualdevice.ReadSCSIBusType(devices, d.Get("scsi_controller_count").(int)))
d.Set("scsi_bus_sharing", virtualdevice.ReadSCSIBusSharing(devices, d.Get("scsi_controller_count").(int)))
// Disks first
if err := virtualdevice.DiskRefreshOperation(d, client, devices); err != nil {
return err
}
// Network devices
if err := virtualdevice.NetworkInterfaceRefreshOperation(d, client, devices); err != nil {
return err
}
// CDROM
if err := virtualdevice.CdromRefreshOperation(d, client, devices); err != nil {
return err
}
// Read tags if we have the ability to do so
if tagsClient, _ := meta.(*VSphereClient).TagsClient(); tagsClient != nil {
if err := readTagsForResource(tagsClient, vm, d); err != nil {
return err
}
}
// Read set custom attributes
if customattribute.IsSupported(client) {
customattribute.ReadFromResource(client, vprops.Entity(), d)
}
// Finally, select a valid IP address for use by the VM for purposes of
// provisioning. This also populates some computed values to present to the
// user.
if vprops.Guest != nil {
if err := buildAndSelectGuestIPs(d, *vprops.Guest); err != nil {
return fmt.Errorf("error reading virtual machine guest data: %s", err)
}
}
log.Printf("[DEBUG] %s: Read complete", resourceVSphereVirtualMachineIDString(d))
return nil
}
func resourceVSphereVirtualMachineUpdate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] %s: Performing update", resourceVSphereVirtualMachineIDString(d))
client := meta.(*VSphereClient).vimClient
tagsClient, err := tagsClientIfDefined(d, meta)
if err != nil {
return err
}
// Verify a proper vCenter before proceeding if custom attributes are defined
attrsProcessor, err := customattribute.GetDiffProcessorIfAttributesDefined(client, d)
if err != nil {
return err
}
id := d.Id()
vm, err := virtualmachine.FromUUID(client, id)
if err != nil {
return fmt.Errorf("cannot locate virtual machine with UUID %q: %s", id, err)
}
if d.HasChange("resource_pool_id") {
var rp *object.ResourcePool
rp, err = resourcepool.FromID(client, d.Get("resource_pool_id").(string))
if err != nil {
return err
}
if err = resourcepool.MoveIntoResourcePool(rp, vm.Reference()); err != nil {
return err
}
// If a VM is moved into or out of a vApp container, the VM's InventoryPath
// will change. This can affect steps later in the update process such as
// moving folders. To make sure the VM has the correct InventoryPath,
// refresh the VM after moving into a new resource pool.
vm, err = virtualmachine.FromMOID(client, vm.Reference().Value)
if err != nil {
return err
}
}
// Update folder if necessary
if d.HasChange("folder") && !vappcontainer.IsVApp(client, d.Get("resource_pool_id").(string)) {
folder := d.Get("folder").(string)
if err := virtualmachine.MoveToFolder(client, vm, folder); err != nil {
return fmt.Errorf("could not move virtual machine to folder %q: %s", folder, err)
}
}
// Apply any pending tags
if tagsClient != nil {
if err := processTagDiff(tagsClient, d, vm); err != nil {
return err
}
}
// Update custom attributes
if attrsProcessor != nil {
if err := attrsProcessor.ProcessDiff(vm); err != nil {
return err
}
}
// Ready to start the VM update. All changes from here, until the update
// operation finishes successfully, need to be done in partial mode.
d.Partial(true)
vprops, err := virtualmachine.Properties(vm)
if err != nil {
return fmt.Errorf("error fetching VM properties: %s", err)
}
spec, changed, err := expandVirtualMachineConfigSpecChanged(d, client, vprops.Config)
if err != nil {
return fmt.Errorf("error in virtual machine configuration: %s", err)
}
devices := object.VirtualDeviceList(vprops.Config.Hardware.Device)
if spec.DeviceChange, err = applyVirtualDevices(d, client, devices); err != nil {
return err
}
// Only carry out the reconfigure if we actually have a change to process.
if changed || len(spec.DeviceChange) > 0 {
//Check to see if we need to shutdown the VM for this process.
if d.Get("reboot_required").(bool) && vprops.Runtime.PowerState != types.VirtualMachinePowerStatePoweredOff {
// Attempt a graceful shutdown of this process. We wrap this in a VM helper.
timeout := d.Get("shutdown_wait_timeout").(int)
force := d.Get("force_power_off").(bool)
if err := virtualmachine.GracefulPowerOff(client, vm, timeout, force); err != nil {
return fmt.Errorf("error shutting down virtual machine: %s", err)
}
}
// Perform updates.
if _, ok := d.GetOk("datastore_cluster_id"); ok {
err = resourceVSphereVirtualMachineUpdateReconfigureWithSDRS(d, meta, vm, spec)
} else {
err = virtualmachine.Reconfigure(vm, spec)
}
if err != nil {
return fmt.Errorf("error reconfiguring virtual machine: %s", err)
}
// Re-fetch properties
vprops, err = virtualmachine.Properties(vm)
if err != nil {
return fmt.Errorf("error re-fetching VM properties after update: %s", err)
}
// Power back on the VM, and wait for network if necessary.
if vprops.Runtime.PowerState != types.VirtualMachinePowerStatePoweredOn {
if err := virtualmachine.PowerOn(vm); err != nil {
return fmt.Errorf("error powering on virtual machine: %s", err)
}
err = virtualmachine.WaitForGuestNet(
client,
vm,
d.Get("wait_for_guest_net_routable").(bool),
d.Get("wait_for_guest_net_timeout").(int),
)
if err != nil {
return err
}
}
}
// Now safe to turn off partial mode.
d.Partial(false)
d.Set("reboot_required", false)
// Now that any pending changes have been done (namely, any disks that don't
// need to be migrated have been deleted), proceed with vMotion if we have
// one pending.
if err := resourceVSphereVirtualMachineUpdateLocation(d, meta); err != nil {
return fmt.Errorf("error running VM migration: %s", err)
}
// All done with updates.
log.Printf("[DEBUG] %s: Update complete", resourceVSphereVirtualMachineIDString(d))
return resourceVSphereVirtualMachineRead(d, meta)
}
// resourceVSphereVirtualMachineUpdateReconfigureWithSDRS runs the reconfigure
// part of resourceVSphereVirtualMachineUpdate through storage DRS. It's
// designed to be run when a storage cluster is specified, versus simply
// specifying datastores.
func resourceVSphereVirtualMachineUpdateReconfigureWithSDRS(
d *schema.ResourceData,
meta interface{},
vm *object.VirtualMachine,
spec types.VirtualMachineConfigSpec,
) error {
// Check to see if we have any disk creation operations first, as sending an
// update through SDRS without any disk creation operations will fail.
if !storagepod.HasDiskCreationOperations(spec.DeviceChange) {
log.Printf("[DEBUG] No disk operations for reconfiguration of VM %q, deferring to standard API", vm.InventoryPath)
return virtualmachine.Reconfigure(vm, spec)
}
client := meta.(*VSphereClient).vimClient
if err := viapi.ValidateVirtualCenter(client); err != nil {
return fmt.Errorf("connection ineligible to use datastore_cluster_id: %s", err)
}
log.Printf("[DEBUG] %s: Reconfiguring virtual machine through Storage DRS API", resourceVSphereVirtualMachineIDString(d))
pod, err := storagepod.FromID(client, d.Get("datastore_cluster_id").(string))
if err != nil {
return fmt.Errorf("error getting datastore cluster: %s", err)
}
err = storagepod.ReconfigureVM(client, vm, spec, pod)
if err != nil {
return fmt.Errorf("error reconfiguring VM on datastore cluster %q: %s", pod.Name(), err)
}
return nil
}
func resourceVSphereVirtualMachineDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] %s: Performing delete", resourceVSphereVirtualMachineIDString(d))
client := meta.(*VSphereClient).vimClient
id := d.Id()
vm, err := virtualmachine.FromUUID(client, id)
if err != nil {
return fmt.Errorf("cannot locate virtual machine with UUID %q: %s", id, err)
}
vprops, err := virtualmachine.Properties(vm)
if err != nil {
return fmt.Errorf("error fetching VM properties: %s", err)
}
// Shutdown the VM first. We do attempt a graceful shutdown for the purpose
// of catching any edge data issues with associated virtual disks that we may
// need to retain on delete. However, we ignore the user-set force shutdown
// flag.
if vprops.Runtime.PowerState != types.VirtualMachinePowerStatePoweredOff {
timeout := d.Get("shutdown_wait_timeout").(int)
if err := virtualmachine.GracefulPowerOff(client, vm, timeout, true); err != nil {
return fmt.Errorf("error shutting down virtual machine: %s", err)
}
}
// Now attempt to detach any virtual disks that may need to be preserved.
devices := object.VirtualDeviceList(vprops.Config.Hardware.Device)
spec := types.VirtualMachineConfigSpec{}
if spec.DeviceChange, err = virtualdevice.DiskDestroyOperation(d, client, devices); err != nil {
return err
}
// Only run the reconfigure operation if there's actually disks in the spec.
if len(spec.DeviceChange) > 0 {
if err := virtualmachine.Reconfigure(vm, spec); err != nil {
return fmt.Errorf("error detaching virtual disks: %s", err)
}
}
// The final operation here is to destroy the VM.
if err := virtualmachine.Destroy(vm); err != nil {
return fmt.Errorf("error destroying virtual machine: %s", err)
}
d.SetId("")
log.Printf("[DEBUG] %s: Delete complete", resourceVSphereVirtualMachineIDString(d))
return nil
}
func resourceVSphereVirtualMachineCustomizeDiff(d *schema.ResourceDiff, meta interface{}) error {
log.Printf("[DEBUG] %s: Performing diff customization and validation", resourceVSphereVirtualMachineIDString(d))
client := meta.(*VSphereClient).vimClient
// Block certain options from being set depending on the vSphere version.
version := viapi.ParseVersionFromClient(client)
if d.Get("efi_secure_boot_enabled").(bool) {
if version.Older(viapi.VSphereVersion{Product: version.Product, Major: 6, Minor: 5}) {
return fmt.Errorf("efi_secure_boot_enabled is only supported on vSphere 6.5 and higher")
}
}
// Validate cdrom sub-resources
if err := virtualdevice.CdromDiffOperation(d, client); err != nil {
return err
}
// Validate network device sub-resources
if err := virtualdevice.NetworkInterfaceDiffOperation(d, client); err != nil {
return err
}
// Process changes to resource pool
if err := resourceVSphereVirtualMachineCustomizeDiffResourcePoolOperation(d); err != nil {
return err
}
// Normalize datastore cluster vs datastore
if err := datastoreClusterDiffOperation(d, client); err != nil {
return err
}
// Validate and normalize disk sub-resources
if err := virtualdevice.DiskDiffOperation(d, client); err != nil {
return err
}
// When a VM is a member of a vApp container, it is no longer part of the VM
// tree, and therefore cannot have its VM folder set.
if _, ok := d.GetOk("folder"); ok && vappcontainer.IsVApp(client, d.Get("resource_pool_id").(string)) {
return fmt.Errorf("cannot set folder while VM is in a vApp container")
}
// If this is a new resource and we are cloning, perform all clone validation
// operations.
if len(d.Get("clone").([]interface{})) > 0 {
if err := viapi.ValidateVirtualCenter(client); err != nil {
return errors.New("use of the clone sub-resource block requires vCenter")
}
switch {
case d.Get("imported").(bool):
// Imported workflows need to have the configuration of the clone
// sub-resource block persisted to state without forcing a new resource.
// Any changes after that will be properly tracked as a ForceNew, by
// flagging the imported flag to off.
d.SetNew("imported", false)
case d.Id() == "":
if err := vmworkflow.ValidateVirtualMachineClone(d, client); err != nil {
return err
}
fallthrough
default:
// For most cases (all non-imported workflows), any changed attribute in
// the clone configuration namespace is a ForceNew. Flag those now.
for _, k := range d.GetChangedKeysPrefix("clone.0") {
if strings.HasSuffix(k, ".#") {
k = strings.TrimSuffix(k, ".#")
}
// To maintain consistency with other timeout options, timeout does not
// need to ForceNew
if k == "clone.0.timeout" {
continue
}
d.ForceNew(k)
}
}
}
// Validate that the config has the necessary components for vApp support.
// Note that for clones the data is prepopulated in
// ValidateVirtualMachineClone.
if err := virtualdevice.VerifyVAppTransport(d, client); err != nil {
return err
}
log.Printf("[DEBUG] %s: Diff customization and validation complete", resourceVSphereVirtualMachineIDString(d))
return nil
}
func resourceVSphereVirtualMachineCustomizeDiffResourcePoolOperation(d *schema.ResourceDiff) error {
if d.HasChange("resource_pool_id") && !d.HasChange("host_system_id") {
log.Printf(
"[DEBUG] %s: resource_pool_id modified without change to host_system_id, marking as computed",
resourceVSphereVirtualMachineIDString(d),
)
if err := d.SetNewComputed("host_system_id"); err != nil {
return err
}
}
return nil
}
func datastoreClusterDiffOperation(d *schema.ResourceDiff, client *govmomi.Client) error {
podID, podOk := d.GetOk("datastore_cluster_id")
podKnown := d.NewValueKnown("datastore_cluster_id")
dsID, dsOk := d.GetOk("datastore_id")
dsKnown := d.NewValueKnown("datastore_id")
switch {
case podKnown && dsKnown && !podOk && !dsOk:
// No root-level datastore option was available. This can happen on new
// configs where the user has not supplied either option, so we need to
// block this.
return errors.New("one of datastore_id datastore_cluster_id must be specified")
case podKnown && !podOk:
// No datastore cluster
return nil
case !dsOk:
// No datastore, we don't need to touch it
return nil
case !podKnown:
// Datastore cluster ID changing but we don't know it yet. Mark the datastore ID as computed
log.Printf("[DEBUG] %s: Datastore cluster ID unknown, marking VM datastore as computed", resourceVSphereVirtualMachineIDString(d))
return d.SetNewComputed("datastore_id")
}
return datastoreClusterDiffOperationCheckMembership(d, client, podID.(string), dsID.(string))
}
func datastoreClusterDiffOperationCheckMembership(d *schema.ResourceDiff, client *govmomi.Client, podID, dsID string) error {
log.Printf("[DEBUG] %s: Checking VM datastore cluster membership", resourceVSphereVirtualMachineIDString(d))
// Determine if the current datastore from state is a member of the current
// datastore cluster.
pod, err := storagepod.FromID(client, podID)
if err != nil {
return fmt.Errorf("error fetching datastore cluster ID %q: %s", podID, err)
}
ds, err := datastore.FromID(client, dsID)
if err != nil {
return fmt.Errorf("error fetching datastore ID %q: %s", dsID, err)
}
isMember, err := storagepod.IsMember(pod, ds)
if err != nil {
return fmt.Errorf("error checking storage pod membership: %s", err)
}
if !isMember {
// If the current datastore in state is not a member of the cluster, we
// need to trigger a migration. Do this by setting the datastore ID to
// computed so that it's picked up in the next update.
log.Printf(
"[DEBUG] %s: Datastore %q not a member of cluster %q, marking VM datastore as computed",
resourceVSphereVirtualMachineIDString(d),
ds.Name(),
pod.Name(),
)
return d.SetNewComputed("datastore_id")
}
return nil
}
func resourceVSphereVirtualMachineImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
client := meta.(*VSphereClient).vimClient
name := d.Id()
if name == "" {
return nil, fmt.Errorf("path cannot be empty")
}
log.Printf("[DEBUG] Looking for VM by name/path %q", name)
vm, err := virtualmachine.FromPath(client, name, nil)
if err != nil {
return nil, fmt.Errorf("error fetching virtual machine: %s", err)
}
props, err := virtualmachine.Properties(vm)
if err != nil {
return nil, fmt.Errorf("error fetching virtual machine properties: %s", err)
}
// Block the import if the VM is a template.
if props.Config.Template {
return nil, fmt.Errorf("VM %q is a template and cannot be imported", name)
}
// Quickly walk the SCSI bus and determine the number of contiguous
// controllers starting from bus number 0. This becomes the current SCSI
// controller count. Anything past this is managed by config.
log.Printf("[DEBUG] Determining number of SCSI controllers for VM %q", name)
scsiBus := make([]bool, 4)
for _, device := range props.Config.Hardware.Device {
sc, ok := device.(types.BaseVirtualSCSIController)
if !ok {
continue
}
scsiBus[sc.GetVirtualSCSIController().BusNumber] = true
}
var ctlrCnt int
for _, v := range scsiBus {
if !v {
break
}
ctlrCnt++
}
if ctlrCnt < 1 {
return nil, fmt.Errorf("VM %q has no SCSI controllers", name)
}
d.Set("scsi_controller_count", ctlrCnt)
// Validate the disks in the VM to make sure that they will work with the
// resource. This is mainly ensuring that all disks are SCSI disks, but a
// Read operation is attempted as well to make sure it will survive that.
if err := virtualdevice.DiskImportOperation(d, client, object.VirtualDeviceList(props.Config.Hardware.Device)); err != nil {
return nil, err
}
// The VM should be ready for reading now
log.Printf("[DEBUG] VM UUID for %q is %q", name, props.Config.Uuid)
d.SetId(props.Config.Uuid)
d.Set("imported", true)
// Set some defaults. This helps possibly prevent diffs where these values
// have not been changed.
rs := resourceVSphereVirtualMachine().Schema
d.Set("force_power_off", rs["force_power_off"].Default)
d.Set("migrate_wait_timeout", rs["migrate_wait_timeout"].Default)
d.Set("shutdown_wait_timeout", rs["shutdown_wait_timeout"].Default)
d.Set("wait_for_guest_net_timeout", rs["wait_for_guest_net_timeout"].Default)
d.Set("wait_for_guest_net_routable", rs["wait_for_guest_net_routable"].Default)
log.Printf("[DEBUG] %s: Import complete, resource is ready for read", resourceVSphereVirtualMachineIDString(d))
return []*schema.ResourceData{d}, nil
}
// resourceVSphereVirtualMachineCreateBare contains the "bare metal" VM
// deploy path. The VM is returned.
func resourceVSphereVirtualMachineCreateBare(d *schema.ResourceData, meta interface{}) (*object.VirtualMachine, error) {
log.Printf("[DEBUG] %s: VM being created from scratch", resourceVSphereVirtualMachineIDString(d))
client := meta.(*VSphereClient).vimClient
poolID := d.Get("resource_pool_id").(string)
pool, err := resourcepool.FromID(client, poolID)
if err != nil {
return nil, fmt.Errorf("could not find resource pool ID %q: %s", poolID, err)
}
// Find the folder based off the path to the resource pool. Basically what we
// are saying here is that the VM folder that we are placing this VM in needs
// to be in the same hierarchy as the resource pool - so in other words, the
// same datacenter.
fo, err := folder.VirtualMachineFolderFromObject(client, pool, d.Get("folder").(string))
if err != nil {
return nil, err
}
var hs *object.HostSystem
if v, ok := d.GetOk("host_system_id"); ok {
hsID := v.(string)
var err error
if hs, err = hostsystem.FromID(client, hsID); err != nil {
return nil, fmt.Errorf("error locating host system at ID %q: %s", hsID, err)
}
}
// Validate that the host is part of the resource pool before proceeding
if err := resourcepool.ValidateHost(client, pool, hs); err != nil {
return nil, err
}
// Ready to start making the VM here. First expand our main config spec.
spec, err := expandVirtualMachineConfigSpec(d, client)
if err != nil {
return nil, fmt.Errorf("error in virtual machine configuration: %s", err)
}
// Now we need to get the default device set - this is available in the
// environment info in the resource pool, which we can then filter through
// our device CRUD lifecycles to get a full deviceChange attribute for our
// configspec.
devices, err := resourcepool.DefaultDevices(client, pool, d.Get("guest_id").(string))
if err != nil {
return nil, fmt.Errorf("error loading default device list: %s", err)
}
log.Printf("[DEBUG] Default devices: %s", virtualdevice.DeviceListString(devices))
if spec.DeviceChange, err = applyVirtualDevices(d, client, devices); err != nil {
return nil, err
}
// Create the VM according the right API path - if we have a datastore
// cluster, use the SDRS API, if not, use the standard API.
var vm *object.VirtualMachine
if _, ok := d.GetOk("datastore_cluster_id"); ok {
vm, err = resourceVSphereVirtualMachineCreateBareWithSDRS(d, meta, fo, spec, pool, hs)
} else {
vm, err = resourceVSphereVirtualMachineCreateBareStandard(d, meta, fo, spec, pool, hs)
}
if err != nil {
return nil, err
}
// VM is created. Set the ID now before proceeding, in case the rest of the
// process here fails.
vprops, err := virtualmachine.Properties(vm)
if err != nil {
return nil, fmt.Errorf("cannot fetch properties of created virtual machine: %s", err)
}
log.Printf("[DEBUG] VM %q - UUID is %q", vm.InventoryPath, vprops.Config.Uuid)
d.SetId(vprops.Config.Uuid)
// Start the virtual machine
if err := virtualmachine.PowerOn(vm); err != nil {
return nil, fmt.Errorf("error powering on virtual machine: %s", err)
}
return vm, nil
}
// resourceVSphereVirtualMachineCreateBareWithSDRS runs the creation part of
// resourceVSphereVirtualMachineCreateBare through storage DRS. It's designed
// to be run when a storage cluster is specified, versus simply specifying
// datastores.
func resourceVSphereVirtualMachineCreateBareWithSDRS(
d *schema.ResourceData,
meta interface{},
fo *object.Folder,
spec types.VirtualMachineConfigSpec,
pool *object.ResourcePool,
hs *object.HostSystem,
) (*object.VirtualMachine, error) {
client := meta.(*VSphereClient).vimClient
if err := viapi.ValidateVirtualCenter(client); err != nil {
return nil, fmt.Errorf("connection ineligible to use datastore_cluster_id: %s", err)
}
log.Printf("[DEBUG] %s: Creating virtual machine through Storage DRS API", resourceVSphereVirtualMachineIDString(d))
pod, err := storagepod.FromID(client, d.Get("datastore_cluster_id").(string))
if err != nil {
return nil, fmt.Errorf("error getting datastore cluster: %s", err)
}
vm, err := storagepod.CreateVM(client, fo, spec, pool, hs, pod)
if err != nil {
return nil, fmt.Errorf("error creating virtual machine on datastore cluster %q: %s", pod.Name(), err)
}
return vm, nil
}
// resourceVSphereVirtualMachineCreateBareStandard performs the steps necessary
// during resourceVSphereVirtualMachineCreateBare to create a virtual machine
// when a datastore cluster is not supplied.
func resourceVSphereVirtualMachineCreateBareStandard(
d *schema.ResourceData,