Created
July 10, 2020 15:51
-
-
Save s9k96/f6205f75e226e3a14cee480e8c2002b1 to your computer and use it in GitHub Desktop.
Lambda function script to list/start/stop an EC2 Instance.
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
""" | |
Lambda function to switch on/off an ec2 instance. | |
Event can be passed like: | |
{ | |
"action" : "list" -> to list all the instances. | |
: "start" -> to start a already set instance. | |
: "stop" -> to stop a alreadt set instance. | |
} | |
""" | |
import json | |
import boto3 | |
region = '' | |
ec2 = boto3.resource('ec2', region_name = region) | |
def list_instances(): | |
''' | |
Lists all the ec2 instances with their state, public Ip, name etc. | |
''' | |
instances = {} | |
for instance in ec2.instances.all(): | |
tags = [i for i in instance.tags if i.get('Value') == 'Cron'] | |
# if len(tags)>0: | |
instances[instance.id] = { | |
"type": instance.instance_type, | |
"public_ip": instance.public_ip_address, | |
"state": instance.state.get('Name'), | |
# "tag": tags | |
} | |
for i in instances.items(): | |
print(i) | |
return instances | |
def start_instance(id): | |
ec2 = boto3.client('ec2') | |
response = ec2.start_instances(InstanceIds=[id], DryRun = False) | |
return response | |
def stop_instance(id): | |
ec2 = boto3.client('ec2') | |
response = ec2.stop_instances(InstanceIds=[id], DryRun=False) | |
return response | |
def reboot_instance(INSTANCE_ID): | |
ec2 = boto3.client('ec2') | |
try: | |
ec2.reboot_instances(InstanceIds=[INSTANCE_ID], DryRun=True) | |
except Exception as e: | |
if 'DryRunOperation' not in str(e): | |
print("You don't have permission to reboot instancess.") | |
raise | |
try: | |
response = ec2.reboot_instances(InstanceIds=[INSTANCE_ID], DryRun=False) | |
print('Success', response) | |
except Exception as e: | |
print('Error', e) | |
def lambda_handler(event, context): | |
# TODO implement | |
data = {} | |
print(event) | |
if event.get('action') == 'list': | |
data = list_instances() | |
print(data) | |
elif event.get('action') == 'start': | |
ins_id = '' | |
data = start_instance(ins_id) | |
elif event.get('action') == 'stop': | |
ins_id = '' | |
data = stop_instance(ins_id) | |
return { | |
'statusCode': 200, | |
'body': json.dumps(data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment