github.phpd.cn/hashicorp/packer@v1.3.2/builder/virtualbox/common/step_run.go (about) 1 package common 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/hashicorp/packer/helper/multistep" 8 "github.com/hashicorp/packer/packer" 9 ) 10 11 // This step starts the virtual machine. 12 // 13 // Uses: 14 // driver Driver 15 // ui packer.Ui 16 // vmName string 17 // 18 // Produces: 19 type StepRun struct { 20 Headless bool 21 22 vmName string 23 } 24 25 func (s *StepRun) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 26 driver := state.Get("driver").(Driver) 27 ui := state.Get("ui").(packer.Ui) 28 vmName := state.Get("vmName").(string) 29 30 ui.Say("Starting the virtual machine...") 31 guiArgument := "gui" 32 if s.Headless { 33 vrdpIpRaw, vrdpIpOk := state.GetOk("vrdpIp") 34 vrdpPortRaw, vrdpPortOk := state.GetOk("vrdpPort") 35 36 if vrdpIpOk && vrdpPortOk { 37 vrdpIp := vrdpIpRaw.(string) 38 vrdpPort := vrdpPortRaw.(uint) 39 40 ui.Message(fmt.Sprintf( 41 "The VM will be run headless, without a GUI. If you want to\n"+ 42 "view the screen of the VM, connect via VRDP without a password to\n"+ 43 "rdp://%s:%d", vrdpIp, vrdpPort)) 44 } else { 45 ui.Message("The VM will be run headless, without a GUI, as configured.\n" + 46 "If the run isn't succeeding as you expect, please enable the GUI\n" + 47 "to inspect the progress of the build.") 48 } 49 guiArgument = "headless" 50 } 51 command := []string{"startvm", vmName, "--type", guiArgument} 52 if err := driver.VBoxManage(command...); err != nil { 53 err := fmt.Errorf("Error starting VM: %s", err) 54 state.Put("error", err) 55 ui.Error(err.Error()) 56 return multistep.ActionHalt 57 } 58 59 s.vmName = vmName 60 61 return multistep.ActionContinue 62 } 63 64 func (s *StepRun) Cleanup(state multistep.StateBag) { 65 if s.vmName == "" { 66 return 67 } 68 69 driver := state.Get("driver").(Driver) 70 ui := state.Get("ui").(packer.Ui) 71 72 if running, _ := driver.IsRunning(s.vmName); running { 73 if err := driver.VBoxManage("controlvm", s.vmName, "poweroff"); err != nil { 74 ui.Error(fmt.Sprintf("Error shutting down VM: %s", err)) 75 } 76 } 77 }