Skip to content

Instantly share code, notes, and snippets.

@mlapida
Last active January 30, 2023 15:09
Show Gist options
  • Star 47 You must be signed in to star a gist
  • Fork 26 You must be signed in to fork a gist
  • Save mlapida/1917b5db84b76b1d1d55 to your computer and use it in GitHub Desktop.
Save mlapida/1917b5db84b76b1d1d55 to your computer and use it in GitHub Desktop.
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
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
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
Copy link
Author

mlapida commented Jul 14, 2016

@tblong

All set.

@tblong
Copy link

tblong commented Jul 15, 2016

@mlapida

Very much appreciated thank you sir!

@esarabadani
Copy link

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

@cs-rodrigo-siviero
Copy link

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

@aaronkjones
Copy link

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
Copy link

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

@sachin-plivo
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.

@shivangitripathi
Copy link

Thank you so much, sir. It's working fine.

@shivangitripathi
Copy link

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"

this is also cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment