github.com/rothwerx/packer@v0.9.0/builder/virtualbox/iso/step_create_vm.go (about) 1 package iso 2 3 import ( 4 "fmt" 5 "github.com/mitchellh/multistep" 6 vboxcommon "github.com/mitchellh/packer/builder/virtualbox/common" 7 "github.com/mitchellh/packer/packer" 8 "time" 9 ) 10 11 // This step creates the actual virtual machine. 12 // 13 // Produces: 14 // vmName string - The name of the VM 15 type stepCreateVM struct { 16 vmName string 17 } 18 19 func (s *stepCreateVM) Run(state multistep.StateBag) multistep.StepAction { 20 config := state.Get("config").(*Config) 21 driver := state.Get("driver").(vboxcommon.Driver) 22 ui := state.Get("ui").(packer.Ui) 23 24 name := config.VMName 25 26 commands := make([][]string, 4) 27 commands[0] = []string{ 28 "createvm", "--name", name, 29 "--ostype", config.GuestOSType, "--register", 30 } 31 commands[1] = []string{ 32 "modifyvm", name, 33 "--boot1", "disk", "--boot2", "dvd", "--boot3", "none", "--boot4", "none", 34 } 35 commands[2] = []string{"modifyvm", name, "--cpus", "1"} 36 commands[3] = []string{"modifyvm", name, "--memory", "512"} 37 38 ui.Say("Creating virtual machine...") 39 for _, command := range commands { 40 err := driver.VBoxManage(command...) 41 if err != nil { 42 err := fmt.Errorf("Error creating VM: %s", err) 43 state.Put("error", err) 44 ui.Error(err.Error()) 45 return multistep.ActionHalt 46 } 47 48 // Set the VM name property on the first command 49 if s.vmName == "" { 50 s.vmName = name 51 } 52 } 53 54 // Set the final name in the state bag so others can use it 55 state.Put("vmName", s.vmName) 56 57 return multistep.ActionContinue 58 } 59 60 func (s *stepCreateVM) Cleanup(state multistep.StateBag) { 61 if s.vmName == "" { 62 return 63 } 64 65 driver := state.Get("driver").(vboxcommon.Driver) 66 ui := state.Get("ui").(packer.Ui) 67 68 ui.Say("Unregistering and deleting virtual machine...") 69 var err error = nil 70 for i := 0; i < 5; i++ { 71 err = driver.VBoxManage("unregistervm", s.vmName, "--delete") 72 if err == nil { 73 break 74 } 75 76 time.Sleep(1 * time.Second * time.Duration(i)) 77 } 78 79 if err != nil { 80 ui.Error(fmt.Sprintf("Error deleting virtual machine: %s", err)) 81 } 82 }