Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using a lambda function, stop all instances that are tagged appropriately.
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:AutoOff',
'Values': ['True']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
#filter the instances
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"

Copyright (c) 2016 Michael Lapidakis

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@tblong

This comment has been minimized.

Copy link

tblong commented Jun 17, 2016

@mlapida Would you be willing to explicitly attach a license to this? I would like to make some mods and include an auto-start script as well. I plan on also providing attribution to you in reference to this gist and the associated blog write up that references this code. Thanks in advance!

@tblong

This comment has been minimized.

Copy link

tblong commented Jul 6, 2016

@mlapida

Just another friendly request reminder to see if you would not mind adding a license to this code.

-Cheers
Tyler

@mlapida

This comment has been minimized.

Copy link
Owner Author

mlapida commented Jul 14, 2016

@tblong

All set.

@tblong

This comment has been minimized.

Copy link

tblong commented Jul 15, 2016

@mlapida

Very much appreciated thank you sir!

@esarabadani

This comment has been minimized.

Copy link

esarabadani commented Jan 3, 2018

Thank you :) sometimes we just need very small and to-the-point samples...

@cs-rodrigo-siviero

This comment has been minimized.

Copy link

cs-rodrigo-siviero commented Jan 4, 2018

is it possible to get instances that are being created(not already running) and if there is no specific tag it terminates?

@aaronkjones

This comment has been minimized.

Copy link

aaronkjones commented Sep 21, 2018

I modified it to start instead of stop:

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:AutoOnOff',
            'Values': ['True']
        },
        {
            'Name': 'instance-state-name', 
            'Values': ['stopped']
        }
    ]
    
    #filter the instances
    instances = ec2.instances.filter(Filters=filters)

    #locate all stopped instances
    StoppedInstances = [instance.id for instance in instances]
    
    #print the instances for logging purposes
    #print StoppedInstances 
    
    #make sure there are actually instances to start. 
    if len(StoppedInstances) > 0:
        #perform the startup
        startingUp = ec2.instances.filter(InstanceIds=StoppedInstances).start()
        print startingUp
    else:
        print "Nothing to see here"
@robert-mundo

This comment has been minimized.

Copy link

robert-mundo commented Apr 17, 2019

If I wanted to search for tags Key is Off and Value is 14d what would I change here

@sachin-plivo

This comment has been minimized.

Copy link

sachin-plivo commented May 6, 2019

How to tweak the same script for the following scenario ?

=> All the instances which do not have the tag "Auto-off" with value "false" should shut down in all the regions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.