github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/builder/hyperv/common/step_create_switch.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  )
     8  
     9  const (
    10  	SwitchTypeInternal = "Internal"
    11  	SwitchTypePrivate  = "Private"
    12  	DefaultSwitchType  = SwitchTypeInternal
    13  )
    14  
    15  // This step creates switch for VM.
    16  //
    17  // Produces:
    18  //   SwitchName string - The name of the Switch
    19  type StepCreateSwitch struct {
    20  	// Specifies the name of the switch to be created.
    21  	SwitchName string
    22  	// Specifies the type of the switch to be created. Allowed values are Internal and Private. To create an External
    23  	// virtual switch, specify either the NetAdapterInterfaceDescription or the NetAdapterName parameter, which
    24  	// implicitly set the type of the virtual switch to External.
    25  	SwitchType string
    26  	// Specifies the name of the network adapter to be bound to the switch to be created.
    27  	NetAdapterName string
    28  	// Specifies the interface description of the network adapter to be bound to the switch to be created.
    29  	NetAdapterInterfaceDescription string
    30  
    31  	createdSwitch bool
    32  }
    33  
    34  func (s *StepCreateSwitch) Run(state multistep.StateBag) multistep.StepAction {
    35  	driver := state.Get("driver").(Driver)
    36  	ui := state.Get("ui").(packer.Ui)
    37  
    38  	if len(s.SwitchType) == 0 {
    39  		s.SwitchType = DefaultSwitchType
    40  	}
    41  
    42  	ui.Say(fmt.Sprintf("Creating switch '%v' if required...", s.SwitchName))
    43  
    44  	createdSwitch, err := driver.CreateVirtualSwitch(s.SwitchName, s.SwitchType)
    45  	if err != nil {
    46  		err := fmt.Errorf("Error creating switch: %s", err)
    47  		state.Put("error", err)
    48  		ui.Error(err.Error())
    49  		s.SwitchName = ""
    50  		return multistep.ActionHalt
    51  	}
    52  
    53  	s.createdSwitch = createdSwitch
    54  
    55  	if !s.createdSwitch {
    56  		ui.Say(fmt.Sprintf("    switch '%v' already exists. Will not delete on cleanup...", s.SwitchName))
    57  	}
    58  
    59  	// Set the final name in the state bag so others can use it
    60  	state.Put("SwitchName", s.SwitchName)
    61  
    62  	return multistep.ActionContinue
    63  }
    64  
    65  func (s *StepCreateSwitch) Cleanup(state multistep.StateBag) {
    66  	if len(s.SwitchName) == 0 || !s.createdSwitch {
    67  		return
    68  	}
    69  
    70  	driver := state.Get("driver").(Driver)
    71  	ui := state.Get("ui").(packer.Ui)
    72  	ui.Say("Unregistering and deleting switch...")
    73  
    74  	err := driver.DeleteVirtualSwitch(s.SwitchName)
    75  	if err != nil {
    76  		ui.Error(fmt.Sprintf("Error deleting switch: %s", err))
    77  	}
    78  }