github.com/mitchellh/packer@v1.3.2/builder/vmware/iso/step_register.go (about)

     1  package iso
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	vmwcommon "github.com/hashicorp/packer/builder/vmware/common"
     9  	"github.com/hashicorp/packer/helper/multistep"
    10  	"github.com/hashicorp/packer/packer"
    11  )
    12  
    13  type StepRegister struct {
    14  	registeredPath string
    15  	Format         string
    16  }
    17  
    18  func (s *StepRegister) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    19  	driver := state.Get("driver").(vmwcommon.Driver)
    20  	ui := state.Get("ui").(packer.Ui)
    21  	vmxPath := state.Get("vmx_path").(string)
    22  
    23  	if remoteDriver, ok := driver.(RemoteDriver); ok {
    24  		ui.Say("Registering remote VM...")
    25  		if err := remoteDriver.Register(vmxPath); err != nil {
    26  			err := fmt.Errorf("Error registering VM: %s", err)
    27  			state.Put("error", err)
    28  			ui.Error(err.Error())
    29  			return multistep.ActionHalt
    30  		}
    31  
    32  		s.registeredPath = vmxPath
    33  	}
    34  
    35  	return multistep.ActionContinue
    36  }
    37  
    38  func (s *StepRegister) Cleanup(state multistep.StateBag) {
    39  	if s.registeredPath == "" {
    40  		return
    41  	}
    42  
    43  	driver := state.Get("driver").(vmwcommon.Driver)
    44  	ui := state.Get("ui").(packer.Ui)
    45  	config := state.Get("config").(*Config)
    46  
    47  	_, cancelled := state.GetOk(multistep.StateCancelled)
    48  	_, halted := state.GetOk(multistep.StateHalted)
    49  	if (config.KeepRegistered) && (!cancelled && !halted) {
    50  		ui.Say("Keeping virtual machine registered with ESX host (keep_registered = true)")
    51  		return
    52  	}
    53  
    54  	if remoteDriver, ok := driver.(RemoteDriver); ok {
    55  		if s.Format == "" || config.SkipExport {
    56  			ui.Say("Unregistering virtual machine...")
    57  			if err := remoteDriver.Unregister(s.registeredPath); err != nil {
    58  				ui.Error(fmt.Sprintf("Error unregistering VM: %s", err))
    59  			}
    60  
    61  			s.registeredPath = ""
    62  		} else {
    63  			ui.Say("Destroying virtual machine...")
    64  			if err := remoteDriver.Destroy(); err != nil {
    65  				ui.Error(fmt.Sprintf("Error destroying VM: %s", err))
    66  			}
    67  			// Wait for the machine to actually destroy
    68  			for {
    69  				destroyed, _ := remoteDriver.IsDestroyed()
    70  				if destroyed {
    71  					break
    72  				}
    73  				time.Sleep(150 * time.Millisecond)
    74  			}
    75  		}
    76  	}
    77  }