refactor: get ssh hot from nics instead of root of the vm

This commit is contained in:
Marin Salinas 2019-09-05 08:21:07 -05:00
parent 793b3f1990
commit 640612da92
1 changed files with 41 additions and 16 deletions

View File

@ -3,6 +3,7 @@ package common
import ( import (
"errors" "errors"
"fmt" "fmt"
"sort"
"time" "time"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
@ -27,35 +28,42 @@ func SSHHost(e oapiDescriber, sshInterface string) func(multistep.StateBag) (str
for j := 0; j <= tries; j++ { for j := 0; j <= tries; j++ {
var host string var host string
i := state.Get("vm").(oapi.Vm) i := state.Get("vm").(oapi.Vm)
if len(i.Nics) <= 0 {
return "", errors.New("couldn't determine address for vm, nics are empty")
}
nic := i.Nics[0]
if sshInterface != "" { if sshInterface != "" {
switch sshInterface { switch sshInterface {
case "public_ip": case "public_ip":
if i.PublicIp != "" { if nic.LinkPublicIp.PublicIp != "" {
host = i.PublicIp host = nic.LinkPublicIp.PublicIp
}
case "private_ip":
if i.PrivateIp != "" {
host = i.PrivateIp
} }
case "public_dns": case "public_dns":
if i.PublicDnsName != "" { if nic.LinkPublicIp.PublicDnsName != "" {
host = i.PublicDnsName host = nic.LinkPublicIp.PublicDnsName
}
case "private_ip":
if privateIP, err := getPrivateIP(nic); err != nil {
host = privateIP.PrivateIp
} }
case "private_dns": case "private_dns":
if i.PrivateDnsName != "" { if privateIP, err := getPrivateIP(nic); err != nil {
host = i.PrivateDnsName host = privateIP.PrivateDnsName
} }
default: default:
panic(fmt.Sprintf("Unknown interface type: %s", sshInterface)) panic(fmt.Sprintf("Unknown interface type: %s", sshInterface))
} }
} else if i.NetId != "" { } else if i.NetId != "" {
if i.PublicIp != "" { if nic.LinkPublicIp.PublicIp != "" {
host = i.PublicIp host = nic.LinkPublicIp.PublicIp
} else if i.PrivateIp != "" { } else if privateIP, err := getPrivateIP(nic); err != nil {
host = i.PrivateIp host = privateIP.PrivateIp
} }
} else if i.PublicDnsName != "" { } else if nic.LinkPublicIp.PublicDnsName != "" {
host = i.PublicDnsName host = nic.LinkPublicIp.PublicDnsName
} }
if host != "" { if host != "" {
@ -82,3 +90,20 @@ func SSHHost(e oapiDescriber, sshInterface string) func(multistep.StateBag) (str
return "", errors.New("couldn't determine address for vm") return "", errors.New("couldn't determine address for vm")
} }
} }
func getPrivateIP(nic oapi.NicLight) (oapi.PrivateIpLightForVm, error) {
isPrimary := true
i := sort.Search(len(nic.PrivateIps), func(i int) bool { return nic.PrivateIps[i].IsPrimary == isPrimary })
if i < len(nic.PrivateIps) && nic.PrivateIps[i].IsPrimary == isPrimary {
return nic.PrivateIps[i], nil
}
if len(nic.PrivateIps) > 0 {
return nic.PrivateIps[0], nil
}
return oapi.PrivateIpLightForVm{}, fmt.Errorf("couldn't determine private address for vm")
}