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

     1  package iso
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"net/url"
     7  	"os"
     8  	"os/exec"
     9  	"runtime"
    10  	"strings"
    11  
    12  	"github.com/hashicorp/packer/packer"
    13  	"github.com/mitchellh/multistep"
    14  )
    15  
    16  type StepExport struct {
    17  	Format     string
    18  	SkipExport bool
    19  	OutputDir  string
    20  }
    21  
    22  func (s *StepExport) generateArgs(c *Config, hidePassword bool) []string {
    23  	password := url.QueryEscape(c.RemotePassword)
    24  	if hidePassword {
    25  		password = "****"
    26  	}
    27  	args := []string{
    28  		"--noSSLVerify=true",
    29  		"--skipManifestCheck",
    30  		"-tt=" + s.Format,
    31  		"vi://" + c.RemoteUser + ":" + password + "@" + c.RemoteHost + "/" + c.VMName,
    32  		s.OutputDir,
    33  	}
    34  	return append(c.OVFToolOptions, args...)
    35  }
    36  
    37  func (s *StepExport) Run(state multistep.StateBag) multistep.StepAction {
    38  	c := state.Get("config").(*Config)
    39  	ui := state.Get("ui").(packer.Ui)
    40  
    41  	// Skip export if requested
    42  	if c.SkipExport {
    43  		ui.Say("Skipping export of virtual machine...")
    44  		return multistep.ActionContinue
    45  	}
    46  
    47  	if c.RemoteType != "esx5" || s.Format == "" {
    48  		ui.Say("Skipping export of virtual machine (export is allowed only for ESXi and the format needs to be specified)...")
    49  		return multistep.ActionContinue
    50  	}
    51  
    52  	ovftool := "ovftool"
    53  	if runtime.GOOS == "windows" {
    54  		ovftool = "ovftool.exe"
    55  	}
    56  
    57  	if _, err := exec.LookPath(ovftool); err != nil {
    58  		err := fmt.Errorf("Error %s not found: %s", ovftool, err)
    59  		state.Put("error", err)
    60  		ui.Error(err.Error())
    61  		return multistep.ActionHalt
    62  	}
    63  
    64  	// Export the VM
    65  	if s.OutputDir == "" {
    66  		s.OutputDir = c.VMName + "." + s.Format
    67  	}
    68  
    69  	if s.Format == "ova" {
    70  		os.MkdirAll(s.OutputDir, 0755)
    71  	}
    72  
    73  	ui.Say("Exporting virtual machine...")
    74  	ui.Message(fmt.Sprintf("Executing: %s %s", ovftool, strings.Join(s.generateArgs(c, true), " ")))
    75  	var out bytes.Buffer
    76  	cmd := exec.Command(ovftool, s.generateArgs(c, false)...)
    77  	cmd.Stdout = &out
    78  	if err := cmd.Run(); err != nil {
    79  		err := fmt.Errorf("Error exporting virtual machine: %s\n%s\n", err, out.String())
    80  		state.Put("error", err)
    81  		ui.Error(err.Error())
    82  		return multistep.ActionHalt
    83  	}
    84  
    85  	ui.Message(fmt.Sprintf("%s", out.String()))
    86  
    87  	return multistep.ActionContinue
    88  }
    89  
    90  func (s *StepExport) Cleanup(state multistep.StateBag) {}