step_stop_instance.go 1.45 KB
Newer Older
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 9 10
	"github.com/mitchellh/packer/packer"
)

Henry Huang's avatar
Henry Huang committed
11 12
type stepStopInstance struct {
	SpotPrice string
13
}
14

15 16 17 18
func (s *stepStopInstance) Run(state multistep.StateBag) multistep.StepAction {
	ec2conn := state.Get("ec2").(*ec2.EC2)
	instance := state.Get("instance").(*ec2.Instance)
	ui := state.Get("ui").(packer.Ui)
19

Henry Huang's avatar
Henry Huang committed
20 21 22 23
	// Skip when it is a spot instance
	if s.SpotPrice != "" {
		return multistep.ActionContinue
	}
24

25 26 27 28
	// Stop the instance so we can create an AMI from it
	ui.Say("Stopping the source instance...")
	_, err := ec2conn.StopInstances(instance.InstanceId)
	if err != nil {
29
		err := fmt.Errorf("Error stopping instance: %s", err)
30
		state.Put("error", err)
31
		ui.Error(err.Error())
32
		return multistep.ActionHalt
33 34 35 36
	}

	// Wait for the instance to actual stop
	ui.Say("Waiting for the instance to stop...")
37 38 39
	stateChange := awscommon.StateChangeConf{
		Pending:   []string{"running", "stopping"},
		Target:    "stopped",
40
		Refresh:   awscommon.InstanceStateRefreshFunc(ec2conn, instance),
41 42
		StepState: state,
	}
43
	_, err = awscommon.WaitForState(&stateChange)
44
	if err != nil {
45
		err := fmt.Errorf("Error waiting for instance to stop: %s", err)
46
		state.Put("error", err)
47
		ui.Error(err.Error())
48
		return multistep.ActionHalt
49 50
	}

51
	return multistep.ActionContinue
52 53
}

54
func (s *stepStopInstance) Cleanup(multistep.StateBag) {
55 56
	// No cleanup...
}