Created
June 16, 2016 13:36
-
-
Save pquery/1364b76cd3407e1bf61c27c13ed68a8e to your computer and use it in GitHub Desktop.
AWS Python Lambda to automatically turn off instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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