diff --git a/builder/amazon/common/ami.go b/builder/amazon/common/ami.go new file mode 100644 index 000000000..6a305aa37 --- /dev/null +++ b/builder/amazon/common/ami.go @@ -0,0 +1,25 @@ +package common + +import ( + "github.com/mitchellh/goamz/ec2" + "log" + "time" +) + +// WaitForAMI waits for the given AMI ID to become ready. +func WaitForAMI(c *ec2.EC2, imageId string) error { + for { + imageResp, err := c.Images([]string{imageId}, ec2.NewFilter()) + if err != nil { + return err + } + + if imageResp.Images[0].State == "available" { + return nil + } + + log.Printf("Image in state %s, sleeping 2s before checking again", + imageResp.Images[0].State) + time.Sleep(2 * time.Second) + } +} diff --git a/builder/amazon/ebs/step_create_ami.go b/builder/amazon/ebs/step_create_ami.go index a33021b49..0b08bc7c9 100644 --- a/builder/amazon/ebs/step_create_ami.go +++ b/builder/amazon/ebs/step_create_ami.go @@ -5,8 +5,8 @@ import ( "fmt" "github.com/mitchellh/goamz/ec2" "github.com/mitchellh/multistep" + awscommon "github.com/mitchellh/packer/builder/amazon/common" "github.com/mitchellh/packer/packer" - "log" "strconv" "text/template" "time" @@ -57,23 +57,11 @@ func (s *stepCreateAMI) Run(state map[string]interface{}) multistep.StepAction { // Wait for the image to become ready ui.Say("Waiting for AMI to become ready...") - for { - imageResp, err := ec2conn.Images([]string{createResp.ImageId}, ec2.NewFilter()) - if err != nil { - err := fmt.Errorf("Error querying images: %s", err) - state["error"] = err - ui.Error(err.Error()) - return multistep.ActionHalt - } - - if imageResp.Images[0].State == "available" { - break - } - - log.Printf("Image in state %s, sleeping 2s before checking again", - imageResp.Images[0].State) - - time.Sleep(2 * time.Second) + if err := awscommon.WaitForAMI(ec2conn, createResp.ImageId); err != nil { + err := fmt.Errorf("Error waiting for AMI: %s", err) + state["error"] = err + ui.Error(err.Error()) + return multistep.ActionHalt } return multistep.ActionContinue diff --git a/builder/amazon/instance/step_register_ami.go b/builder/amazon/instance/step_register_ami.go index 56ce784b9..d95deb888 100644 --- a/builder/amazon/instance/step_register_ami.go +++ b/builder/amazon/instance/step_register_ami.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/mitchellh/goamz/ec2" "github.com/mitchellh/multistep" + awscommon "github.com/mitchellh/packer/builder/amazon/common" "github.com/mitchellh/packer/packer" "strconv" "text/template" @@ -52,6 +53,15 @@ func (s *StepRegisterAMI) Run(state map[string]interface{}) multistep.StepAction amis[config.Region] = registerResp.ImageId state["amis"] = amis + // Wait for the image to become ready + ui.Say("Waiting for AMI to become ready...") + if err := awscommon.WaitForAMI(ec2conn, registerResp.ImageId); err != nil { + err := fmt.Errorf("Error waiting for AMI: %s", err) + state["error"] = err + ui.Error(err.Error()) + return multistep.ActionHalt + } + return multistep.ActionContinue }