Shell script: Terminate an Amazon EC2 instance

Amazon web servicesHow can we terminate a specified Amazon EC2 step by step with the help of Amazon commandline tools?

It’s not difficult.
Typically, you might have been attached at least one EBS volume to your instance, which means you need to detach and delete them when terminating the instance. A general list of steps is listed below, which can be used for very common usage:

  1. Get a list of volumes that attached to the instances, excluding the boot device like /dev/sda.
  2. Detach and delete these volumes one by one.
  3. Terminate the instance finally.

A bash script can be used for this task:

#!/bin/bash
#
# This script is for terminating Amazon EC2 instances, and releasing all the attached
# EBS volumes.
# Created by Joseph.Chen, released under GPL v2
#  https://www.admon.org/

version="20101105"

test EC2_CERT || echo "EC_CERT is not set, which is needed"
test EC2_PRIVATE_KEY || echo "EC2_PRIVATE_KEY is needed which is not set"

# ec2_help()
## list some examples on creating new instance.
ec2_help()
{
  echo
  show_version
  echo "`basename $0` instance-id"
  echo "This script terminates the specified instance and releases the attached volume accordingly."
  echo
  echo "Example:"
  echo "    `basename $0` Instance-ID  --- Terminal the specified instance id completely."
  echo
  exit
}

show_version()
{
  echo "`basename $0` Version number is $version"
}

[ $# -ne "1" ] && ec2_help
instance_id=$1

echo "You're about to delete a micro instance completely on Amazon EC2,"
read -p "     Press any key to continue, or Ctrl + C to quit... " -s -n 1

volume_info=$(ec2-describe-instances $instance_id |grep ^BLOCK |grep -v /dev/sda |awk '{print $3}')
[ $? -eq "0" ] && {
  echo "Volumes that attached to this server: $volume_info "
  echo "They all will be released"
} || exit

for volume in $volume_info
do
  ec2-detach-volume $volume #Error in this step can be ignored
  sleep 5 #We need to wait a short while
  ec2-delete-volume $volume || echo Error occured when deleting $volume
done

ec2-terminate-instances $instance_id
[ $? -eq "0" ] && {
  echo "It's OK now!"
} || {
  echo "Got some issues when terminating the instance $instance_id"
}

I’ve ever faced a issue when releasing EBS storage from commandline, the volume cannot be released normally. As this issue is rare to see, you can read the details here, and all you need to do is to add –force to ec2-detach-volume.

Share Button

Leave a comment

Your email address will not be published. Required fields are marked *