This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
/
step_create_switch.go
68 lines (53 loc) · 1.72 KB
/
step_create_switch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package common
import (
"fmt"
"bytes"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
)
// This step creates switch for VM.
//
// Produces:
// SwitchName string - The name of the Switch
type StepCreateSwitch struct {
SwitchName string
}
func (s *StepCreateSwitch) Run(state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
ui.Say("Creating internal switch...")
var blockBuffer bytes.Buffer
blockBuffer.WriteString("Invoke-Command -scriptblock {$TestSwitch = Get-VMSwitch -Name '")
blockBuffer.WriteString(s.SwitchName)
blockBuffer.WriteString("' -ErrorAction SilentlyContinue; if ($TestSwitch.Count -EQ 0){New-VMSwitch -Name '")
blockBuffer.WriteString(s.SwitchName)
blockBuffer.WriteString("' -SwitchType Internal}}")
err := driver.HypervManage( blockBuffer.String() )
if err != nil {
err := fmt.Errorf("Error creating switch: %s", err)
state.Put("error", err)
ui.Error(err.Error())
s.SwitchName = "";
return multistep.ActionHalt
}
// Set the final name in the state bag so others can use it
state.Put("SwitchName", s.SwitchName)
return multistep.ActionContinue
}
func (s *StepCreateSwitch) Cleanup(state multistep.StateBag) {
if s.SwitchName == "" {
return
}
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
ui.Say("Unregistering and deleting switch...")
var err error = nil
var blockBuffer bytes.Buffer
blockBuffer.WriteString("Invoke-Command -scriptblock {Remove-VMSwitch '")
blockBuffer.WriteString(s.SwitchName)
blockBuffer.WriteString("' -Force}")
err = driver.HypervManage( blockBuffer.String() )
if err != nil {
ui.Error(fmt.Sprintf("Error deleting switch: %s", err))
}
}