2013-07-29 21:13:22 -04:00
|
|
|
package chroot
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2015-04-05 17:58:48 -04:00
|
|
|
"log"
|
|
|
|
|
2017-02-25 14:08:53 -05:00
|
|
|
"github.com/aws/aws-sdk-go/aws/ec2metadata"
|
|
|
|
"github.com/aws/aws-sdk-go/aws/session"
|
2015-06-03 17:13:52 -04:00
|
|
|
"github.com/aws/aws-sdk-go/service/ec2"
|
2018-01-19 19:18:44 -05:00
|
|
|
"github.com/hashicorp/packer/helper/multistep"
|
2017-04-04 16:39:01 -04:00
|
|
|
"github.com/hashicorp/packer/packer"
|
2017-06-09 13:40:50 -04:00
|
|
|
)
|
2013-07-29 21:13:22 -04:00
|
|
|
|
|
|
|
// StepInstanceInfo verifies that this builder is running on an EC2 instance.
|
|
|
|
type StepInstanceInfo struct{}
|
|
|
|
|
2013-08-31 15:58:55 -04:00
|
|
|
func (s *StepInstanceInfo) Run(state multistep.StateBag) multistep.StepAction {
|
|
|
|
ec2conn := state.Get("ec2").(*ec2.EC2)
|
2017-12-19 14:04:17 -05:00
|
|
|
session := state.Get("awsSession").(*session.Session)
|
2013-08-31 15:58:55 -04:00
|
|
|
ui := state.Get("ui").(packer.Ui)
|
2013-07-29 21:13:22 -04:00
|
|
|
|
|
|
|
// Get our own instance ID
|
|
|
|
ui.Say("Gathering information about this EC2 instance...")
|
2017-02-25 14:08:53 -05:00
|
|
|
|
2017-12-19 14:04:17 -05:00
|
|
|
ec2meta := ec2metadata.New(session)
|
2017-02-25 14:08:53 -05:00
|
|
|
identity, err := ec2meta.GetInstanceIdentityDocument()
|
2013-07-29 21:13:22 -04:00
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf(
|
|
|
|
"Error retrieving the ID of the instance Packer is running on.\n" +
|
|
|
|
"Please verify Packer is running on a proper AWS EC2 instance.")
|
2013-08-31 15:58:55 -04:00
|
|
|
state.Put("error", err)
|
2013-07-29 21:13:22 -04:00
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
2017-02-25 14:08:53 -05:00
|
|
|
log.Printf("Instance ID: %s", identity.InstanceID)
|
2013-07-29 21:13:22 -04:00
|
|
|
|
|
|
|
// Query the entire instance metadata
|
2017-02-25 14:08:53 -05:00
|
|
|
instancesResp, err := ec2conn.DescribeInstances(&ec2.DescribeInstancesInput{InstanceIds: []*string{&identity.InstanceID}})
|
2013-07-29 21:13:22 -04:00
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error getting instance data: %s", err)
|
2013-08-31 15:58:55 -04:00
|
|
|
state.Put("error", err)
|
2013-07-29 21:13:22 -04:00
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(instancesResp.Reservations) == 0 {
|
|
|
|
err := fmt.Errorf("Error getting instance data: no instance found.")
|
2013-08-31 15:58:55 -04:00
|
|
|
state.Put("error", err)
|
2013-07-29 21:13:22 -04:00
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
2015-06-22 18:08:41 -04:00
|
|
|
instance := instancesResp.Reservations[0].Instances[0]
|
2013-08-31 15:58:55 -04:00
|
|
|
state.Put("instance", instance)
|
2013-07-29 21:13:22 -04:00
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
2013-08-31 15:58:55 -04:00
|
|
|
func (s *StepInstanceInfo) Cleanup(multistep.StateBag) {}
|