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