github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/virtualbox/common/step_export.go (about)

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