2020-06-11 12:37:32 -04:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
|
2020-11-17 19:31:03 -05:00
|
|
|
"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
|
2020-06-11 12:37:32 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// Step to discover the http ip
|
|
|
|
// which guests use to reach the vm host
|
|
|
|
// To make sure the IP is set before boot command and http server steps
|
|
|
|
type StepHTTPIPDiscover struct {
|
2020-06-17 01:36:55 -04:00
|
|
|
HTTPIP string
|
|
|
|
Network *net.IPNet
|
2020-06-11 12:37:32 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StepHTTPIPDiscover) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
|
2020-06-17 01:36:55 -04:00
|
|
|
ip, err := getHostIP(s.HTTPIP, s.Network)
|
2020-06-11 12:37:32 -04:00
|
|
|
if err != nil {
|
|
|
|
state.Put("error", err)
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
state.Put("http_ip", ip)
|
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *StepHTTPIPDiscover) Cleanup(state multistep.StateBag) {}
|
|
|
|
|
2020-06-17 01:36:55 -04:00
|
|
|
func getHostIP(s string, network *net.IPNet) (string, error) {
|
2020-06-11 12:37:32 -04:00
|
|
|
if s != "" {
|
|
|
|
if net.ParseIP(s) != nil {
|
|
|
|
return s, nil
|
|
|
|
} else {
|
|
|
|
return "", fmt.Errorf("invalid IP address")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
addrs, err := net.InterfaceAddrs()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2020-06-17 01:46:30 -04:00
|
|
|
// look for an IP that is contained in the ip_wait_address range
|
2020-06-17 11:40:39 -04:00
|
|
|
if network != nil {
|
|
|
|
for _, a := range addrs {
|
|
|
|
ipnet, ok := a.(*net.IPNet)
|
|
|
|
if ok && !ipnet.IP.IsLoopback() {
|
|
|
|
if network.Contains(ipnet.IP) {
|
|
|
|
return ipnet.IP.String(), nil
|
|
|
|
}
|
2020-06-11 12:37:32 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-06-17 01:46:30 -04:00
|
|
|
|
|
|
|
// fallback to an ipv4 address if an IP is not found in the range
|
|
|
|
for _, a := range addrs {
|
|
|
|
ipnet, ok := a.(*net.IPNet)
|
|
|
|
if ok && !ipnet.IP.IsLoopback() {
|
|
|
|
if ipnet.IP.To4() != nil {
|
|
|
|
return ipnet.IP.String(), nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-06-11 12:37:32 -04:00
|
|
|
return "", fmt.Errorf("IP not found")
|
|
|
|
}
|