github.com/sneal/packer@v0.5.2/builder/virtualbox/common/step_export.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  	"log"
     8  	"path/filepath"
     9  	"time"
    10  )
    11  
    12  // This step cleans up forwarded ports and exports the VM to an OVF.
    13  //
    14  // Uses:
    15  //
    16  // Produces:
    17  //   exportPath string - The path to the resulting export.
    18  type StepExport struct {
    19  	Format    string
    20  	OutputDir string
    21  }
    22  
    23  func (s *StepExport) Run(state multistep.StateBag) multistep.StepAction {
    24  	driver := state.Get("driver").(Driver)
    25  	ui := state.Get("ui").(packer.Ui)
    26  	vmName := state.Get("vmName").(string)
    27  
    28  	// Wait a second to ensure VM is really shutdown.
    29  	log.Println("1 second timeout to ensure VM is really shutdown")
    30  	time.Sleep(1 * time.Second)
    31  
    32  	// Clear out the Packer-created forwarding rule
    33  	ui.Say("Preparing to export machine...")
    34  	ui.Message(fmt.Sprintf(
    35  		"Deleting forwarded port mapping for SSH (host port %d)",
    36  		state.Get("sshHostPort")))
    37  	command := []string{"modifyvm", vmName, "--natpf1", "delete", "packerssh"}
    38  	if err := driver.VBoxManage(command...); err != nil {
    39  		err := fmt.Errorf("Error deleting port forwarding rule: %s", err)
    40  		state.Put("error", err)
    41  		ui.Error(err.Error())
    42  		return multistep.ActionHalt
    43  	}
    44  
    45  	// Export the VM to an OVF
    46  	outputPath := filepath.Join(s.OutputDir, vmName+"."+s.Format)
    47  
    48  	command = []string{
    49  		"export",
    50  		vmName,
    51  		"--output",
    52  		outputPath,
    53  	}
    54  
    55  	ui.Say("Exporting virtual machine...")
    56  	err := driver.VBoxManage(command...)
    57  	if err != nil {
    58  		err := fmt.Errorf("Error exporting virtual machine: %s", err)
    59  		state.Put("error", err)
    60  		ui.Error(err.Error())
    61  		return multistep.ActionHalt
    62  	}
    63  
    64  	state.Put("exportPath", outputPath)
    65  
    66  	return multistep.ActionContinue
    67  }
    68  
    69  func (s *StepExport) Cleanup(state multistep.StateBag) {}