func awsTerminateInstance(conn *ec2.EC2, id string) error {
	log.Printf("[INFO] Terminating instance: %s", id)
	req := &ec2.TerminateInstancesInput{
		InstanceIds: []*string{aws.String(id)},
	if _, err := conn.TerminateInstances(req); err != nil {
		return fmt.Errorf("Error terminating instance: %s", err)

	log.Printf("[DEBUG] Waiting for instance (%s) to become terminated", id)

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"pending", "running", "shutting-down", "stopped", "stopping"},
		Target:     []string{"terminated"},
		Refresh:    InstanceStateRefreshFunc(conn, id),
		Timeout:    10 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,

	_, err := stateConf.WaitForState()
	if err != nil {
		return fmt.Errorf(
			"Error waiting for instance (%s) to terminate: %s", id, err)

	return nil
Example #2
// This function will terminate a set of instances based on the ID.  It takes a
// slice of strings and calls the API to stop them all.  It will return nil if
// there are no problems.
func termInstance(instanceids []string, ec2client *ec2.EC2) error {
	// Create our struct to hold everything
	instanceReq := ec2.TerminateInstancesInput{
		InstanceIds: []*string{},

	// Loop through our input array and add them to our struct, converting them to the string pointer required by the SDK
	for _, id := range instanceids {
		instanceReq.InstanceIds = append(instanceReq.InstanceIds, aws.String(id))

	//Make the request to kill all the instances, returning an error if we got one.
	instanceResp, err := ec2client.TerminateInstances(&instanceReq)
	if err != nil {
		return err

	// The number of instances we got back should be the same as how many we requested.
	if len(instanceResp.TerminatingInstances) != len(instanceids) {
		return errors.New("The total number of stopped instances did not match the request")

	// Finally, let's loop through all of the responses and see they aren't all terminated.
	// We'll store each ID in a string so we can build a good error and use it to see later if we had any unterminated
	allterminated := ""

	// Loop through all the instances and check the state
	for _, instance := range instanceResp.TerminatingInstances {
		if *instance.CurrentState.Code != INSTANCE_STATE_TERMINATED && *instance.CurrentState.Code != INSTANCE_STATE_SHUTTING_DOWN {
			allterminated = allterminated + " " + *instance.InstanceId

	// If we found some that didn't terminate then return the rror
	if allterminated != "" {
		return errors.New("The following instances were not properly terminated: " + allterminated)

	// Else let's return nil for success
	return nil