github.com/mitchellh/packer@v1.3.2/builder/virtualbox/common/step_export.go (about)

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