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

     1  package chroot
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  
     8  	"github.com/aws/aws-sdk-go/aws/ec2metadata"
     9  	"github.com/aws/aws-sdk-go/aws/session"
    10  	"github.com/aws/aws-sdk-go/service/ec2"
    11  	"github.com/hashicorp/packer/helper/multistep"
    12  	"github.com/hashicorp/packer/packer"
    13  )
    14  
    15  // StepInstanceInfo verifies that this builder is running on an EC2 instance.
    16  type StepInstanceInfo struct{}
    17  
    18  func (s *StepInstanceInfo) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    19  	ec2conn := state.Get("ec2").(*ec2.EC2)
    20  	session := state.Get("awsSession").(*session.Session)
    21  	ui := state.Get("ui").(packer.Ui)
    22  
    23  	// Get our own instance ID
    24  	ui.Say("Gathering information about this EC2 instance...")
    25  
    26  	ec2meta := ec2metadata.New(session)
    27  	identity, err := ec2meta.GetInstanceIdentityDocument()
    28  	if err != nil {
    29  		err := fmt.Errorf(
    30  			"Error retrieving the ID of the instance Packer is running on.\n" +
    31  				"Please verify Packer is running on a proper AWS EC2 instance.")
    32  		state.Put("error", err)
    33  		ui.Error(err.Error())
    34  		return multistep.ActionHalt
    35  	}
    36  	log.Printf("Instance ID: %s", identity.InstanceID)
    37  
    38  	// Query the entire instance metadata
    39  	instancesResp, err := ec2conn.DescribeInstances(&ec2.DescribeInstancesInput{InstanceIds: []*string{&identity.InstanceID}})
    40  	if err != nil {
    41  		err := fmt.Errorf("Error getting instance data: %s", err)
    42  		state.Put("error", err)
    43  		ui.Error(err.Error())
    44  		return multistep.ActionHalt
    45  	}
    46  
    47  	if len(instancesResp.Reservations) == 0 {
    48  		err := fmt.Errorf("Error getting instance data: no instance found.")
    49  		state.Put("error", err)
    50  		ui.Error(err.Error())
    51  		return multistep.ActionHalt
    52  	}
    53  
    54  	instance := instancesResp.Reservations[0].Instances[0]
    55  	state.Put("instance", instance)
    56  
    57  	return multistep.ActionContinue
    58  }
    59  
    60  func (s *StepInstanceInfo) Cleanup(multistep.StateBag) {}