github.com/mitchellh/packer@v1.3.2/builder/virtualbox/ovf/step_import.go (about)

     1  package ovf
     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 imports an OVF VM into VirtualBox.
    13  type StepImport struct {
    14  	Name        string
    15  	ImportFlags []string
    16  
    17  	vmName string
    18  }
    19  
    20  func (s *StepImport) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    21  	driver := state.Get("driver").(vboxcommon.Driver)
    22  	ui := state.Get("ui").(packer.Ui)
    23  	vmPath := state.Get("vm_path").(string)
    24  
    25  	ui.Say(fmt.Sprintf("Importing VM: %s", vmPath))
    26  	if err := driver.Import(s.Name, vmPath, s.ImportFlags); err != nil {
    27  		err := fmt.Errorf("Error importing VM: %s", err)
    28  		state.Put("error", err)
    29  		ui.Error(err.Error())
    30  		return multistep.ActionHalt
    31  	}
    32  
    33  	s.vmName = s.Name
    34  	state.Put("vmName", s.Name)
    35  	return multistep.ActionContinue
    36  }
    37  
    38  func (s *StepImport) Cleanup(state multistep.StateBag) {
    39  	if s.vmName == "" {
    40  		return
    41  	}
    42  
    43  	driver := state.Get("driver").(vboxcommon.Driver)
    44  	ui := state.Get("ui").(packer.Ui)
    45  	config := state.Get("config").(*Config)
    46  
    47  	_, cancelled := state.GetOk(multistep.StateCancelled)
    48  	_, halted := state.GetOk(multistep.StateHalted)
    49  	if (config.KeepRegistered) && (!cancelled && !halted) {
    50  		ui.Say("Keeping virtual machine registered with VirtualBox host (keep_registered = true)")
    51  		return
    52  	}
    53  
    54  	ui.Say("Deregistering and deleting imported VM...")
    55  	if err := driver.Delete(s.vmName); err != nil {
    56  		ui.Error(fmt.Sprintf("Error deleting VM: %s", err))
    57  	}
    58  }