@ -2,14 +2,19 @@ package cloudstack
import (
"fmt"
"math/rand"
"strings"
"time"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
"github.com/xanzy/go-cloudstack/cloudstack"
)
type stepSetupNetworking struct { }
type stepSetupNetworking struct {
privatePort int
publicPort int
}
func ( s * stepSetupNetworking ) Run ( state multistep . StateBag ) multistep . StepAction {
client := state . Get ( "client" ) . ( * cloudstack . CloudStackClient )
@ -24,6 +29,21 @@ func (s *stepSetupNetworking) Run(state multistep.StateBag) multistep.StepAction
return multistep . ActionContinue
}
// Generate a random public port used to configure our port forward.
rand . Seed ( time . Now ( ) . UnixNano ( ) )
s . publicPort = 50000 + rand . Intn ( 10000 )
// Set the currently configured port to be the private port.
s . privatePort = config . Comm . Port ( )
// Set the SSH or WinRM port to be the randomly generated public port.
switch config . Comm . Type {
case "ssh" :
config . Comm . SSHPort = s . publicPort
case "winrm" :
config . Comm . WinRMPort = s . publicPort
}
// Retrieve the instance ID from the previously saved state.
instanceID , ok := state . Get ( "instance_id" ) . ( string )
if ! ok || instanceID == "" {
@ -54,10 +74,6 @@ func (s *stepSetupNetworking) Run(state multistep.StateBag) multistep.StepAction
p . SetNetworkid ( network . Id )
}
if config . Zone != "" {
p . SetZoneid ( config . Zone )
}
// Associate a new public IP address.
ipAddr , err := client . Address . AssociateIpAddress ( p )
if err != nil {
@ -76,9 +92,9 @@ func (s *stepSetupNetworking) Run(state multistep.StateBag) multistep.StepAction
ui . Message ( "Creating port forward..." )
p := client . Firewall . NewCreatePortForwardingRuleParams (
config . PublicIPAddress ,
config. Comm . Port ( ) ,
s. privatePort ,
"TCP" ,
config. Comm . Port ( ) ,
s. publicPort ,
instanceID ,
)
@ -110,8 +126,8 @@ func (s *stepSetupNetworking) Run(state multistep.StateBag) multistep.StepAction
p . SetAclid ( network . Aclid )
p . SetAction ( "allow" )
p . SetCidrlist ( config . CIDRList )
p . SetStartport ( config. Comm . Port ( ) )
p . SetEndport ( config. Comm . Port ( ) )
p . SetStartport ( s. privatePort )
p . SetEndport ( s. privatePort )
p . SetTraffictype ( "ingress" )
// Create the network ACL rule.
@ -131,8 +147,8 @@ func (s *stepSetupNetworking) Run(state multistep.StateBag) multistep.StepAction
// Configure the firewall rule.
p . SetCidrlist ( config . CIDRList )
p . SetStartport ( config. Comm . Port ( ) )
p . SetEndport ( config. Comm . Port ( ) )
p . SetStartport ( s. publicPort )
p . SetEndport ( s. publicPort )
fwRule , err := client . Firewall . CreateFirewallRule ( p )
if err != nil {