packer-cn/builder/amazon/ebs/step_create_ami.go

87 lines
2.4 KiB
Go
Raw Normal View History

package ebs
import (
"fmt"
"github.com/mitchellh/goamz/ec2"
"github.com/mitchellh/multistep"
awscommon "github.com/mitchellh/packer/builder/amazon/common"
"github.com/mitchellh/packer/packer"
)
type stepCreateAMI struct {
image *ec2.Image
}
2013-08-31 16:00:43 -04:00
func (s *stepCreateAMI) Run(state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(config)
ec2conn := state.Get("ec2").(*ec2.EC2)
instance := state.Get("instance").(*ec2.Instance)
ui := state.Get("ui").(packer.Ui)
// Create the image
ui.Say(fmt.Sprintf("Creating the AMI: %s", config.AMIName))
createOpts := &ec2.CreateImage{
InstanceId: instance.InstanceId,
Name: config.AMIName,
BlockDevices: config.BlockDevices.BuildAMIDevices(),
}
createResp, err := ec2conn.CreateImage(createOpts)
if err != nil {
err := fmt.Errorf("Error creating AMI: %s", err)
2013-08-31 16:00:43 -04:00
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
// Set the AMI ID in the state
imagesResp, err := ec2conn.Images([]string{createResp.ImageId}, nil)
if err != nil {
err := fmt.Errorf("Error searching for AMI: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
s.image = &imagesResp.Images[0]
2013-12-12 15:24:51 -05:00
ui.Message(fmt.Sprintf("AMI: %s", createResp.ImageId))
amis := make(map[string]string)
2013-07-29 19:42:35 -04:00
amis[ec2conn.Region.Name] = createResp.ImageId
2013-08-31 16:00:43 -04:00
state.Put("amis", amis)
// Wait for the image to become ready
stateChange := awscommon.StateChangeConf{
Pending: []string{"pending"},
Target: "available",
Refresh: awscommon.AMIStateRefreshFunc(ec2conn, createResp.ImageId),
StepState: state,
}
ui.Say("Waiting for AMI to become ready...")
if _, err := awscommon.WaitForState(&stateChange); err != nil {
err := fmt.Errorf("Error waiting for AMI: %s", err)
2013-08-31 16:00:43 -04:00
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
return multistep.ActionContinue
}
func (s *stepCreateAMI) Cleanup(state multistep.StateBag) {
if s.image == nil {
return
}
ec2conn := state.Get("ec2").(*ec2.EC2)
ui := state.Get("ui").(packer.Ui)
ui.Say("Deregistering the AMI ...")
if resp, err := ec2conn.DeregisterImage(s.image.Id); err != nil {
ui.Error(fmt.Sprintf("Error deregistering AMI, may still be around: %s", err))
return
} else if resp.Return == false {
ui.Error(fmt.Sprintf("Error deregistering AMI, may still be around: %s", resp.Return))
return
}
}