Terminate all EC2 instances

The Amazon Elastic Compute Cloud (EC2) allows you to quickly launch virtual servers in the cloud. If you create an AMI (Amazon Machine Image), you can deploy many instances of this image, only limited by your instance limit (20 initially, but you can request more).

Amazon Management Console
Amazon Management Console

The instances can be manged through the AWS management console web-interface, for example to create multiple instances as shown above.

However, this console does not have a convenient method to terminate all the running instances – you have to terminate them one-by-one! This becomes a big problem if you, like me, are launching 1000s of instances for a few hours and then want to take them all down again. Since you are getting charged by the instance hour, you don’t want them running longer than necessary.

EC2 API tools

Fortunately, the EC2 API Tools provide an alternate interface to EC2. These tools rely on a Java runtime, and a few environment variables to install. They seem to work best with Linux, but I have not tested them on Windows myself. There are some guides available on how to install them, for example the Ubuntu EC2 Starters Guide. If you already have an AWS account, you should get them working within 10 minutes on Ubuntu.

Now that you have command-line access to managing the instances, you have much more power to do mass-management of them.

Terminating all instances

Assuming you’ve got EC2 API tools installed and working correctly above, you probably noticed a command that can help terminate the instances: ec2-terminate-instances. However, this command assumes the instance IDs that are to be terminated as parameters — there is no option to terminate all. Looking further at the tools, there is a command called ec2-describe-instances that returns the instance IDs of the running instances (among other things).

So our task is to get the running instance IDs from ec2-describe-instances and pass them as a parameter to ec2-terminate-instances. With some helper commands, this can be achieved as follows.

ec2-describe-instances | grep INSTANCE | awk '{print $2}' | xargs ec2-terminate-instances

Be careful: this will terminate all your running instances, so don’t run it if you don’t mean it! If you have a lot of instances to terminate, ec2-terminate-instances may report that reading from the network socket failed (due to a timeout). But the termination will nonetheless succeed, as you can confirm from the AWS management console.

This has saved me hours of one-by-one termination from the web interface, and I hope it can help you too.

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

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

four − = 0