github.com/alouche/packer@v0.3.7/builder/vmware/step_clean_vmx.go (about)

     1  package vmware
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  	"io/ioutil"
     8  	"log"
     9  	"os"
    10  	"regexp"
    11  	"strings"
    12  )
    13  
    14  // This step cleans up the VMX by removing or changing this prior to
    15  // being ready for use.
    16  //
    17  // Uses:
    18  //   ui     packer.Ui
    19  //   vmx_path string
    20  //
    21  // Produces:
    22  //   <nothing>
    23  type stepCleanVMX struct{}
    24  
    25  func (s stepCleanVMX) Run(state multistep.StateBag) multistep.StepAction {
    26  	isoPath := state.Get("iso_path").(string)
    27  	ui := state.Get("ui").(packer.Ui)
    28  	vmxPath := state.Get("vmx_path").(string)
    29  
    30  	ui.Say("Cleaning VMX prior to finishing up...")
    31  
    32  	vmxData, err := s.readVMX(vmxPath)
    33  	if err != nil {
    34  		state.Put("error", fmt.Errorf("Error reading VMX: %s", err))
    35  		return multistep.ActionHalt
    36  	}
    37  
    38  	if _, ok := state.GetOk("floppy_path"); ok {
    39  		// Delete the floppy0 entries so the floppy is no longer mounted
    40  		ui.Message("Unmounting floppy from VMX...")
    41  		for k, _ := range vmxData {
    42  			if strings.HasPrefix(k, "floppy0.") {
    43  				log.Printf("Deleting key: %s", k)
    44  				delete(vmxData, k)
    45  			}
    46  		}
    47  		vmxData["floppy0.present"] = "FALSE"
    48  	}
    49  
    50  	ui.Message("Detaching ISO from CD-ROM device...")
    51  	devRe := regexp.MustCompile(`^ide\d:\d\.`)
    52  	for k, _ := range vmxData {
    53  		match := devRe.FindString(k)
    54  		if match == "" {
    55  			continue
    56  		}
    57  
    58  		filenameKey := match + ".filename"
    59  		if filename, ok := vmxData[filenameKey]; ok {
    60  			if filename == isoPath {
    61  				// Change the CD-ROM device back to auto-detect to eject
    62  				vmxData[filenameKey] = "auto detect"
    63  				vmxData[match+".deviceType"] = "cdrom-raw"
    64  			}
    65  		}
    66  	}
    67  
    68  	// Rewrite the VMX
    69  	if err := WriteVMX(vmxPath, vmxData); err != nil {
    70  		state.Put("error", fmt.Errorf("Error writing VMX: %s", err))
    71  		return multistep.ActionHalt
    72  	}
    73  
    74  	return multistep.ActionContinue
    75  }
    76  
    77  func (stepCleanVMX) Cleanup(multistep.StateBag) {}
    78  
    79  func (stepCleanVMX) readVMX(vmxPath string) (map[string]string, error) {
    80  	vmxF, err := os.Open(vmxPath)
    81  	if err != nil {
    82  		return nil, err
    83  	}
    84  	defer vmxF.Close()
    85  
    86  	vmxBytes, err := ioutil.ReadAll(vmxF)
    87  	if err != nil {
    88  		return nil, err
    89  	}
    90  
    91  	return ParseVMX(string(vmxBytes)), nil
    92  }