Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pquery
Created June 16, 2016 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pquery/1364b76cd3407e1bf61c27c13ed68a8e to your computer and use it in GitHub Desktop.
Save pquery/1364b76cd3407e1bf61c27c13ed68a8e to your computer and use it in GitHub Desktop.
AWS Python Lambda to automatically turn off instances
import boto3
import botocore
import logging
import requests
# setup simple logging for INFO
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
success="SUCCESS"
def lambda_handler(event, context):
turnOff()
return success
def locator():
# make a request call to the meta-data to find the region
r = requests.get('http://169.254.169.254/latest/meta-data/placement/availability-zone/')
az = r.text
region = az[:-1]
print(region)
return region
def turnOff(region):
# Setup up the boto3
ec2 = boto3.resource('ec2',region_name=region)
ec2_client = boto3.client('ec2',region_name=region)
# Use the filter() method of the instances collection
# to retrieve all the 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("Found the following running instances" + RunningInstances)
# Turn off the instance
for instance in RunningInstances:
try:
ec2Stop = ec2.instances.stop(instance)
except botocore.exceptions.ClientError, e:
logger.error(e)
pass
#turnOff()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment