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