github.phpd.cn/hashicorp/packer@v1.3.2/builder/googlecompute/step_instance_info.go (about)

     1  package googlecompute
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"time"
     8  
     9  	"github.com/hashicorp/packer/helper/multistep"
    10  	"github.com/hashicorp/packer/packer"
    11  )
    12  
    13  // stepInstanceInfo represents a Packer build step that gathers GCE instance info.
    14  type StepInstanceInfo struct {
    15  	Debug bool
    16  }
    17  
    18  // Run executes the Packer build step that gathers GCE instance info.
    19  // This adds "instance_ip" to the multistep state.
    20  func (s *StepInstanceInfo) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    21  	config := state.Get("config").(*Config)
    22  	driver := state.Get("driver").(Driver)
    23  	ui := state.Get("ui").(packer.Ui)
    24  
    25  	instanceName := state.Get("instance_name").(string)
    26  
    27  	ui.Say("Waiting for the instance to become running...")
    28  	errCh := driver.WaitForInstance("RUNNING", config.Zone, instanceName)
    29  	var err error
    30  	select {
    31  	case err = <-errCh:
    32  	case <-time.After(config.stateTimeout):
    33  		err = errors.New("time out while waiting for instance to become running")
    34  	}
    35  
    36  	if err != nil {
    37  		err := fmt.Errorf("Error waiting for instance: %s", err)
    38  		state.Put("error", err)
    39  		ui.Error(err.Error())
    40  		return multistep.ActionHalt
    41  	}
    42  
    43  	if config.UseInternalIP {
    44  		ip, err := driver.GetInternalIP(config.Zone, instanceName)
    45  		if err != nil {
    46  			err := fmt.Errorf("Error retrieving instance internal ip address: %s", err)
    47  			state.Put("error", err)
    48  			ui.Error(err.Error())
    49  			return multistep.ActionHalt
    50  		}
    51  
    52  		if s.Debug {
    53  			if ip != "" {
    54  				ui.Message(fmt.Sprintf("Internal IP: %s", ip))
    55  			}
    56  		}
    57  		ui.Message(fmt.Sprintf("IP: %s", ip))
    58  		state.Put("instance_ip", ip)
    59  		return multistep.ActionContinue
    60  	} else {
    61  		ip, err := driver.GetNatIP(config.Zone, instanceName)
    62  		if err != nil {
    63  			err := fmt.Errorf("Error retrieving instance nat ip address: %s", err)
    64  			state.Put("error", err)
    65  			ui.Error(err.Error())
    66  			return multistep.ActionHalt
    67  		}
    68  
    69  		if s.Debug {
    70  			if ip != "" {
    71  				ui.Message(fmt.Sprintf("Public IP: %s", ip))
    72  			}
    73  		}
    74  		ui.Message(fmt.Sprintf("IP: %s", ip))
    75  		state.Put("instance_ip", ip)
    76  		return multistep.ActionContinue
    77  	}
    78  }
    79  
    80  // Cleanup.
    81  func (s *StepInstanceInfo) Cleanup(state multistep.StateBag) {}