github.com/alouche/packer@v0.3.7/builder/vmware/host_ip_ifconfig.go (about)

     1  package vmware
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"os/exec"
     7  	"regexp"
     8  )
     9  
    10  // IfconfigIPFinder finds the host IP based on the output of `ifconfig`.
    11  type IfconfigIPFinder struct {
    12  	Device string
    13  }
    14  
    15  func (f *IfconfigIPFinder) HostIP() (string, error) {
    16  	ifconfigPath, err := exec.LookPath("ifconfig")
    17  	if err != nil {
    18  		return "", err
    19  	}
    20  
    21  	stdout := new(bytes.Buffer)
    22  
    23  	cmd := exec.Command(ifconfigPath, f.Device)
    24  	cmd.Stdout = stdout
    25  	cmd.Stderr = new(bytes.Buffer)
    26  	if err := cmd.Run(); err != nil {
    27  		return "", err
    28  	}
    29  
    30  	re := regexp.MustCompile(`inet\s*(?:addr:)?(.+?)\s`)
    31  	matches := re.FindStringSubmatch(stdout.String())
    32  	if matches == nil {
    33  		return "", errors.New("IP not found in ifconfig output...")
    34  	}
    35  
    36  	return matches[1], nil
    37  }