Created
April 20, 2017 05:33
-
-
Save melvinlee/eeddb48c1d93350de68eca0cc3c5e3ee to your computer and use it in GitHub Desktop.
Lambda Autostart and autostop EC2 instance
This file contains hidden or 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 | |
ec2 = boto3.resource('ec2') | |
print('Loading function') | |
def lambda_handler(event, context): | |
instance = list_autostop_instance() | |
stop_instances(instance) | |
def find_name(instance): | |
''' Find instance name | |
''' | |
for tags in instance.tags: | |
if tags["Key"] == 'Name': | |
return tags["Value"] | |
def list_running_instances(): | |
''' List of running instance | |
''' | |
instances = ec2.instances.filter( | |
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) | |
for instance in instances: | |
print(instance.id, instance.instance_type) | |
def list_autostart_instance(): | |
'''Retrieving autostart instance Ec2 | |
''' | |
print("Locating EC2 instance with autostart tag...") | |
instancelist = [] | |
filters = [{'Name':'tag:AutoStart', 'Values':['Yes']}] | |
instances = ec2.instances.filter(Filters=filters) | |
for instance in instances: | |
instancelist.append(instance.id) | |
print(instance.id, find_name(instance), instance.instance_type) | |
return instancelist | |
def list_autostop_instance(): | |
'''Retrieving autostop instance Ec2 | |
''' | |
print("Locating EC2 instance with autostop tag...") | |
instancelist = [] | |
filters = [{'Name':'tag:AutoStop', 'Values':['Yes']}] | |
instances = ec2.instances.filter(Filters=filters) | |
for instance in instances: | |
instancelist.append(instance.id) | |
print(instance.id, find_name(instance), instance.instance_type) | |
return instancelist | |
def start_instances(ids): | |
'''Start EC2 instances by specifying Id | |
''' | |
ec2.instances.filter(InstanceIds=ids).start() | |
for instance_id in ids: | |
print("Starting instance {}".format(instance_id)) | |
def stop_instances(ids): | |
''' Stop running EC2 instance by specifying Id | |
''' | |
ec2.instances.filter(InstanceIds=ids).stop() | |
for instance_id in ids: | |
print("Stoping instance {}".format(instance_id)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment