How can I kill all my EC2 instances from the command line?

0 votes
asked Mar 12, 2009 by flybywire

How can I kill all my instances from the command line? Is there a command for this or must I script it?

4 Answers

0 votes
answered Mar 12, 2009 by kgiannakakis

As far as I know there isn't an 'all' switch for the ec2-terminate-instances command. So you probably need to script it. It won't be that hard. You only need to generate a comma separated list of your instances.

This is a python script I am using:

import sys
import time
from boto.ec2.connection import EC2Connection

def main():
    conn = EC2Connection('', '')
    instances = conn.get_all_instances()
    print instances
    for reserv in instances:
        for inst in reserv.instances:
            if inst.state == u'running':
                print "Terminating instance %s" % inst
                inst.stop()

if __name__ == "__main__":
    main()

It uses boto library. This is not necessary for the specific task (a simple shell script will be enough), but it may be handy in many occasions.

Finally are you aware of Elasticfox extension for Firefox? This is by far the easiest way to access EC2.

0 votes
answered Mar 12, 2009 by adamk

AWS Console and Elasticfox make it pretty easy.

A command-line solution can be achieved in one-line using the EC2 API tools:

for i in `ec2din | grep running | cut -f2`; do ec2kill $i; done
0 votes
answered Mar 6, 2016 by belmin-fernandez

This is an old question but thought I'd share a solution for AWS CLI:

$ aws ec2 terminate-instances --instance-ids $(aws ec2 describe-instances --filters  "Name=instance-state-name,Values=pending,running,stopped,stopping" --query "Reservations[].Instances[].[InstanceId]" --output text | tr '\n' ' ')
0 votes
answered Sep 15, 2017 by lorenz-lo-sauer

For completeness sake. Here's another way, being more in line with the repertoire of a programmer, by using regular expressions and the aws cli:

aws ec2 terminate-instances 
        --instance-ids 
         $(
          aws ec2 describe-instances 
            | grep InstanceId 
            | awk {'print $2'} 
            | sed 's/[",]//g'
          )
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...