github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/builder/hyperv/common/step_create_external_switch.go (about) 1 package common 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/hashicorp/packer/common/uuid" 8 "github.com/hashicorp/packer/helper/multistep" 9 "github.com/hashicorp/packer/packer" 10 ) 11 12 // This step creates switch for VM. 13 // 14 // Produces: 15 // SwitchName string - The name of the Switch 16 type StepCreateExternalSwitch struct { 17 SwitchName string 18 oldSwitchName string 19 } 20 21 func (s *StepCreateExternalSwitch) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 22 driver := state.Get("driver").(Driver) 23 ui := state.Get("ui").(packer.Ui) 24 25 vmName := state.Get("vmName").(string) 26 errorMsg := "Error creating external switch: %s" 27 var err error 28 29 ui.Say("Creating external switch...") 30 31 packerExternalSwitchName := "paes_" + uuid.TimeOrderedUUID() 32 33 err = driver.CreateExternalVirtualSwitch(vmName, packerExternalSwitchName) 34 if err != nil { 35 err := fmt.Errorf("Error creating switch: %s", err) 36 state.Put(errorMsg, err) 37 ui.Error(err.Error()) 38 s.SwitchName = "" 39 return multistep.ActionHalt 40 } 41 42 switchName, err := driver.GetVirtualMachineSwitchName(vmName) 43 if err != nil { 44 err := fmt.Errorf(errorMsg, err) 45 state.Put("error", err) 46 ui.Error(err.Error()) 47 return multistep.ActionHalt 48 } 49 50 if len(switchName) == 0 { 51 err := fmt.Errorf(errorMsg, err) 52 state.Put("error", "Can't get the VM switch name") 53 ui.Error(err.Error()) 54 return multistep.ActionHalt 55 } 56 57 ui.Say("External switch name is: '" + switchName + "'") 58 59 if switchName != packerExternalSwitchName { 60 s.SwitchName = "" 61 } else { 62 s.SwitchName = packerExternalSwitchName 63 s.oldSwitchName = state.Get("SwitchName").(string) 64 } 65 66 // Set the final name in the state bag so others can use it 67 state.Put("SwitchName", switchName) 68 69 return multistep.ActionContinue 70 } 71 72 func (s *StepCreateExternalSwitch) Cleanup(state multistep.StateBag) { 73 if s.SwitchName == "" { 74 return 75 } 76 driver := state.Get("driver").(Driver) 77 ui := state.Get("ui").(packer.Ui) 78 vmName := state.Get("vmName").(string) 79 80 ui.Say("Unregistering and deleting external switch...") 81 82 var err error = nil 83 84 errMsg := "Error deleting external switch: %s" 85 86 // connect the vm to the old switch 87 if s.oldSwitchName == "" { 88 ui.Error(fmt.Sprintf(errMsg, "the old switch name is empty")) 89 return 90 } 91 92 err = driver.ConnectVirtualMachineNetworkAdapterToSwitch(vmName, s.oldSwitchName) 93 if err != nil { 94 ui.Error(fmt.Sprintf(errMsg, err)) 95 return 96 } 97 98 state.Put("SwitchName", s.oldSwitchName) 99 100 err = driver.DeleteVirtualSwitch(s.SwitchName) 101 if err != nil { 102 ui.Error(fmt.Sprintf(errMsg, err)) 103 } 104 }