2013-12-24 01:27:01 -05:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2013-12-24 13:00:51 -05:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2020-05-28 16:36:45 -04:00
|
|
|
"net"
|
2013-12-24 01:27:01 -05:00
|
|
|
|
2018-01-19 19:18:44 -05:00
|
|
|
"github.com/hashicorp/packer/helper/multistep"
|
2013-12-24 01:27:01 -05:00
|
|
|
)
|
|
|
|
|
2015-06-13 19:23:33 -04:00
|
|
|
func CommHost(config *SSHConfig) func(multistep.StateBag) (string, error) {
|
2013-12-24 13:00:51 -05:00
|
|
|
return func(state multistep.StateBag) (string, error) {
|
|
|
|
driver := state.Get("driver").(Driver)
|
2020-05-30 03:17:18 -04:00
|
|
|
comm := config.Comm
|
2013-12-24 13:00:51 -05:00
|
|
|
|
2020-05-30 03:17:18 -04:00
|
|
|
// Figure out which protocol we're using to communicate with the
|
|
|
|
// guest, and determine the correct port to handshake with.
|
|
|
|
port := comm.SSHPort
|
|
|
|
if comm.SSHHost != "" {
|
|
|
|
return comm.SSHHost, nil
|
|
|
|
}
|
|
|
|
if comm.Type == "winrm" {
|
|
|
|
port = comm.WinRMPort
|
2014-03-28 18:22:37 -04:00
|
|
|
}
|
|
|
|
|
2020-05-30 03:17:18 -04:00
|
|
|
// Get the list of potential addresses that the guest might use.
|
|
|
|
hosts, err := driver.PotentialGuestIP(state)
|
2013-12-24 13:00:51 -05:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("IP lookup failed: %s", err)
|
|
|
|
return "", fmt.Errorf("IP lookup failed: %s", err)
|
|
|
|
}
|
|
|
|
|
2020-05-30 03:17:18 -04:00
|
|
|
if len(hosts) == 0 {
|
2013-12-24 13:00:51 -05:00
|
|
|
log.Println("IP is blank, no IP yet.")
|
|
|
|
return "", errors.New("IP is blank")
|
|
|
|
}
|
|
|
|
|
2020-05-28 16:36:45 -04:00
|
|
|
// Iterate through our list of addresses and dial each one. This way we
|
|
|
|
// can dial up each one to see which lease is actually correct and has
|
|
|
|
// ssh up.
|
2020-05-30 03:17:18 -04:00
|
|
|
for index, host := range hosts {
|
|
|
|
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, port))
|
2020-05-28 16:36:45 -04:00
|
|
|
|
|
|
|
// If we got a connection, then we should be good to go. Return the
|
|
|
|
// address to the caller and pray that things work out.
|
|
|
|
if err == nil {
|
|
|
|
conn.Close()
|
|
|
|
|
2020-05-30 03:17:18 -04:00
|
|
|
log.Printf("Detected IP: %s", host)
|
|
|
|
return host, nil
|
2020-05-28 16:36:45 -04:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise we need to iterate to the next entry and keep hoping.
|
2020-05-30 03:17:18 -04:00
|
|
|
log.Printf("Ignoring entry %d at %s:%d due to host being down.", index, host, port)
|
2020-05-28 16:36:45 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return "", errors.New("Host is not up")
|
2013-12-24 13:00:51 -05:00
|
|
|
}
|
|
|
|
}
|