Skip to content

Instantly share code, notes, and snippets.

@smd877
Created October 1, 2018 05:07
Show Gist options
  • Save smd877/7b8a1f2eb8346c1e6b5fcc2d69dcef07 to your computer and use it in GitHub Desktop.
Save smd877/7b8a1f2eb8346c1e6b5fcc2d69dcef07 to your computer and use it in GitHub Desktop.
AWS Lambda ControlEC2 Code
import boto3
def lambda_handler(event, context):
command = event.get('command')
if command in ['start', 'stop', 'status']:
try:
instance = boto3.resource('ec2').Instance(event.get('target'))
state = instance.state['Name']
if command == 'start' and state == 'stopped':
instance.start()
elif command == 'stop' and state == 'running':
instance.stop()
else:
command = 'status'
ip = instance.public_ip_address
return createReturn([command, state, ip], None)
except Exception as e:
return createReturn(None, e.args)
else:
return createReturn(None, 'Request Error.')
def createReturn(successes, errors):
ret = dict()
ret['result'] = errors is None
if errors is None:
ret['message'] = 'command={}, state={}, ip={}'.format(successes[0], successes[1], successes[2])
else:
ret['message'] = errors
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment