Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import boto3, botocore, json
ec2_client = boto3.client('ec2', region_name='ap-northeast-1')
lambda_client = boto3.client('lambda', region_name='ap-northeast-1')
def validation_event(event):
if len(event) == 0:
print 'There is no Event source.'
return False
if not event.has_key("command"):
print "There is no command."
return False
if not event.has_key("instance_id"):
print "There is no instance_id."
return False
return True
def lambda_handler(event, context):
if validation_event(event) is False:
raise Exception('400: Bad Request')
if event[u'command'] == "stop":
ec2_client.stop_instances(
DryRun=False,
InstanceIds=[
event[u'instance_id'],
]
)
print "Waiting for stopping instance: %s." % event[u'instance_id']
ec2_client.get_waiter('instance_stopped').wait(
DryRun=False,
InstanceIds=[
event[u'instance_id'],
],
)
# Invoke start lambda function
input = {
"instance_id": event[u'instance_id'],
"command": "start"
}
try:
response = lambda_client.invoke(
FunctionName='Mackerel-Webhook-Restart-Instance',
InvocationType='Event',
Payload=json.dumps(input)
)
except Exception, e:
print e
raise Exception('500: Internal Server Error')
if response[u'StatusCode'] != 202:
print response
raise Exception('500: Internal Server Error')
return
elif event[u'command'] == "start":
ec2_client.start_instances(
DryRun=False,
InstanceIds=[
event[u'instance_id'],
]
)
print "Waiting for starting instance: %s." % event[u'instance_id']
ec2_client.get_waiter('system_status_ok').wait(
DryRun=False,
InstanceIds=[
event[u'instance_id'],
]
)
# Invoke check lambda function
input = {
"instance_id": event[u'instance_id'],
"command": "check"
}
try:
response = lambda_client.invoke(
FunctionName='Mackerel-Webhook-Restart-Instance',
InvocationType='Event',
Payload=json.dumps(input)
)
except Exception, e:
print e
raise Exception('500: Internal Server Error')
if response[u'StatusCode'] != 202:
print response
raise Exception('500: Internal Server Error')
return
elif event[u'command'] == "check":
print "Check about starting instance: %s." % event[u'instance_id']
waiter = ec2_client.get_waiter('instance_status_ok')
# waiting for 4 minutes (= 15 sec * 16 count)
waiter.config.delay = 15
waiter.config.max_attempts = 16
try:
waiter.wait(
DryRun=False,
InstanceIds=[
event[u'instance_id'],
]
)
except botocore.exceptions.WaiterError as e:
# Max attempts exceeded
# Invoke stop(restart) lambda function
input = {
"instance_id": event[u'instance_id'],
"command": "stop"
}
response = lambda_client.invoke(
FunctionName='Mackerel-Webhook-Restart-Instance',
InvocationType='Event',
Payload=json.dumps(input)
)
except Exception, e:
print e
raise Exception('500: Internal Server Error')
return
else:
raise Exception('400: Bad Request')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.