-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep_fetch_vm.go
89 lines (73 loc) · 1.89 KB
/
step_fetch_vm.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
package main
import (
"context"
"strings"
"github.com/hashicorp/packer/packer"
"github.com/mitchellh/multistep"
"github.com/vmware/govmomi/find"
)
type StepFetchVm struct {
VMName string
Source string
}
func (s *StepFetchVm) Run(state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
ctx := state.Get("context").(context.Context)
f := state.Get("finder").(*find.Finder)
ui.Say("Fetching VM...")
if err := avoidOrphaned(ctx, f, s.VMName); err != nil {
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
path := strings.Split(s.Source, "/vmfs/volumes/")[1]
i := strings.Index(path, "/")
storage := path[:i]
vmx := path[i:]
ds, err := f.DatastoreOrDefault(ctx, storage)
if err != nil {
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
folder, err := f.DefaultFolder(ctx)
if err != nil {
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
pool, err := f.DefaultResourcePool(ctx)
if err != nil {
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
task, err := folder.RegisterVM(ctx, ds.Path(vmx), s.VMName, false, pool, nil)
if err != nil {
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if err = task.Wait(ctx); err != nil {
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
vm, err := f.VirtualMachine(ctx, s.VMName)
if err != nil {
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
state.Put("vm", vm)
return multistep.ActionContinue
}
// When ESXI remove the VM, vSphere keep the VM as orphaned
func avoidOrphaned(ctx context.Context, f *find.Finder, vm_name string) error {
vm, err := f.VirtualMachine(ctx, vm_name)
if err != nil {
return err
}
return vm.Unregister(ctx)
}
func (s *StepFetchVm) Cleanup(multistep.StateBag) {}