github.com/alouche/packer@v0.3.7/builder/virtualbox/step_create_vm.go (about)

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