Boto 3 – Python script for shutting down EC2 AWS instances based on tags

Posted: March 8, 2019 in AWS, Scripts

Stop all instances

Script for shutting down instances which are:

  • in running state
  • don’t have tag “AutoStopEnabled” set to “True”
import boto3
import logging

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

#define the connection
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):

   # Use the filter() method of the instances collection to retrieve
    # all running EC2 instances.
   filters = [
             {
            'Name': 'tag:AutoStopEnabled',
            'Values': ['True']
        },
        {
            'Name': 'instance-state-name',
            'Values': ['running']
        }
    ]

    #filter the instances
    #ec2 = boto3.client('ec2', region_name=region)
   instances = ec2.instances.filter(Filters=filters)

    #locate all running instances
   RunningInstances = [instance.id for instance in instances]

    #print the instances for logging purposes
   print (RunningInstances) 

    #make sure there are actually instances to shut down.
   if len(RunningInstances) > 0:
        #perform the shutdown
        shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
        #print shuttingDown
   else:
    print "Nothing to see here"

Stop all instances except ones with specific tag

Following script will do opposite:

Will shut down all instances which are:

  • in running state
  • which don’t have tag “AutoOff” at all or have tag “AutoOff” set to “False”
import boto3
import logging

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

#define the connection
ec2 = boto3.resource('ec2')
# open connection to ec2
#conn = get_ec2_conn()

# get a list of all instances
# all_instances = [i for i in ec2.instances.all()]
# get list of all running instances

all_instances = [i for i in ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])]
def lambda_handler(event, context):

    #instances = ec2.instances.filter(Filters=filters)
    # get instances with filter of running + with tag `Name`
    instances = [i for i in ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}, {'Name':'tag:AutoOff', 'Values':['False']}])]

    # make a list of filtered instances IDs `[i.id for i in instances]`
    # Filter from all instances the instance that are not in the filtered list
    instances_to_stop = [to_stop for to_stop in all_instances if to_stop.id not in [i.id for i in instances]]

    # run over your `instances_to_stop` list and stop each one of them
    for instance in instances_to_stop:
        instance.stop()

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s