Created
October 1, 2018 05:07
-
-
Save smd877/7b8a1f2eb8346c1e6b5fcc2d69dcef07 to your computer and use it in GitHub Desktop.
AWS Lambda ControlEC2 Code
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 | |
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