github.phpd.cn/hashicorp/packer@v1.3.2/builder/hyperv/common/step_configure_ip.go (about)

     1  package common
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/hashicorp/packer/helper/multistep"
    11  	"github.com/hashicorp/packer/packer"
    12  )
    13  
    14  type StepConfigureIp struct {
    15  }
    16  
    17  func (s *StepConfigureIp) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    18  	driver := state.Get("driver").(Driver)
    19  	ui := state.Get("ui").(packer.Ui)
    20  
    21  	errorMsg := "Error configuring ip address: %s"
    22  	vmName := state.Get("vmName").(string)
    23  
    24  	ui.Say("Configuring ip address...")
    25  
    26  	count := 60
    27  	var duration time.Duration = 1
    28  	sleepTime := time.Minute * duration
    29  	var ip string
    30  
    31  	for count != 0 {
    32  		cmdOut, err := driver.GetVirtualMachineNetworkAdapterAddress(vmName)
    33  		if err != nil {
    34  			err := fmt.Errorf(errorMsg, err)
    35  			state.Put("error", err)
    36  			ui.Error(err.Error())
    37  			return multistep.ActionHalt
    38  		}
    39  
    40  		ip = strings.TrimSpace(cmdOut)
    41  
    42  		if ip != "False" {
    43  			break
    44  		}
    45  
    46  		log.Println(fmt.Sprintf("Waiting for another %v minutes...", uint(duration)))
    47  		time.Sleep(sleepTime)
    48  		count--
    49  	}
    50  
    51  	if count == 0 {
    52  		err := fmt.Errorf(errorMsg, "IP address assigned to the adapter is empty")
    53  		state.Put("error", err)
    54  		ui.Error(err.Error())
    55  		return multistep.ActionHalt
    56  	}
    57  
    58  	ui.Say("ip address is " + ip)
    59  
    60  	hostName, err := driver.GetHostName(ip)
    61  	if err != nil {
    62  		state.Put("error", err)
    63  		ui.Error(err.Error())
    64  		return multistep.ActionHalt
    65  	}
    66  
    67  	ui.Say("hostname is " + hostName)
    68  
    69  	state.Put("ip", ip)
    70  	state.Put("hostname", hostName)
    71  
    72  	return multistep.ActionContinue
    73  }
    74  
    75  func (s *StepConfigureIp) Cleanup(state multistep.StateBag) {
    76  	// do nothing
    77  }