github.com/jbronn/packer@v0.1.6-0.20140120165540-8a1364dbd817/builder/amazon/ebs/step_create_ami.go (about)

     1  package ebs
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/goamz/ec2"
     6  	"github.com/mitchellh/multistep"
     7  	awscommon "github.com/mitchellh/packer/builder/amazon/common"
     8  	"github.com/mitchellh/packer/packer"
     9  )
    10  
    11  type stepCreateAMI struct{}
    12  
    13  func (s *stepCreateAMI) Run(state multistep.StateBag) multistep.StepAction {
    14  	config := state.Get("config").(config)
    15  	ec2conn := state.Get("ec2").(*ec2.EC2)
    16  	instance := state.Get("instance").(*ec2.Instance)
    17  	ui := state.Get("ui").(packer.Ui)
    18  
    19  	// Create the image
    20  	ui.Say(fmt.Sprintf("Creating the AMI: %s", config.AMIName))
    21  	createOpts := &ec2.CreateImage{
    22  		InstanceId:   instance.InstanceId,
    23  		Name:         config.AMIName,
    24  		BlockDevices: config.BlockDevices.BuildAMIDevices(),
    25  	}
    26  
    27  	createResp, err := ec2conn.CreateImage(createOpts)
    28  	if err != nil {
    29  		err := fmt.Errorf("Error creating AMI: %s", err)
    30  		state.Put("error", err)
    31  		ui.Error(err.Error())
    32  		return multistep.ActionHalt
    33  	}
    34  
    35  	// Set the AMI ID in the state
    36  	ui.Message(fmt.Sprintf("AMI: %s", createResp.ImageId))
    37  	amis := make(map[string]string)
    38  	amis[ec2conn.Region.Name] = createResp.ImageId
    39  	state.Put("amis", amis)
    40  
    41  	// Wait for the image to become ready
    42  	stateChange := awscommon.StateChangeConf{
    43  		Pending:   []string{"pending"},
    44  		Target:    "available",
    45  		Refresh:   awscommon.AMIStateRefreshFunc(ec2conn, createResp.ImageId),
    46  		StepState: state,
    47  	}
    48  
    49  	ui.Say("Waiting for AMI to become ready...")
    50  	if _, err := awscommon.WaitForState(&stateChange); err != nil {
    51  		err := fmt.Errorf("Error waiting for AMI: %s", err)
    52  		state.Put("error", err)
    53  		ui.Error(err.Error())
    54  		return multistep.ActionHalt
    55  	}
    56  
    57  	return multistep.ActionContinue
    58  }
    59  
    60  func (s *stepCreateAMI) Cleanup(multistep.StateBag) {
    61  	// No cleanup...
    62  }