Created
February 28, 2016 05:21
-
-
Save Tmorinaga/5b1df9e90e20fe173685 to your computer and use it in GitHub Desktop.
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 | |
import json | |
client = boto3.client('ec2') | |
def lambda_handler(event, context): | |
print 'Start Lambda function(StopEC2 by Tag)' | |
detail = event['detail'] | |
instance_id = detail['instance-id'] | |
if instance_id is None: | |
print 'There is no Instance ID' | |
return 'false' | |
# Show Instance ID/state | |
print "Check start Target instance ID =" + instance_id | |
print 'State= '+ str(detail['state']) | |
if detail['state'] != 'pending': | |
return "Status fail" | |
# Exec descibeinstances by instance-id | |
# About boto ec2.describe-instaces check below link | |
# http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Client.describe_instances | |
res_json = client.describe_instances( | |
DryRun = False, | |
Filters=[{'Name':'instance-id', 'Values':[instance_id]}] | |
) | |
HTTP_code = res_json['ResponseMetadata']['HTTPStatusCode'] | |
if str(HTTP_code) != '200': | |
print 'describe instances command fail: HTTP responce=' + str(HTTP_code) | |
res = res_json['Reservations'].pop() | |
Instance_info = res['Instances'].pop() | |
#Tag check | |
if check_Tags(Instance_info, instance_id) == 'true': | |
return 'Tags are Okay' | |
else: | |
return 'Need to Setup the mandatory key' | |
context.done('end of Lambda') | |
# Check Tag key | |
# Input:Tags [associative array] | |
# Output:true/false | |
def check_Tags(Instance_info, instance_id): | |
#defined | |
MANDATORY_KEYNAME='Cost' | |
if Instance_info.has_key('Tags'): | |
tags = Instance_info['Tags'] | |
else: | |
exec_stop_Instance(instance_id) | |
return | |
for tag in tags: | |
print tag.get('Key') | |
if tag.get('Key') == MANDATORY_KEYNAME: | |
return 'true' | |
exec_stop_Instance(instance_id) | |
return 'false' | |
# Execute EC2 stop | |
# Input: Instance-ID | |
# Output: none | |
def exec_stop_Instance(instance_id): | |
print 'There is no Mandatory Tag' | |
print 'Instance Stop :' + instance_id | |
# See datail:http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Client.stop_instances | |
ret = client.stop_instances( | |
DryRun=False, | |
InstanceIds=[instance_id] | |
) | |
print 'Execute Instance Stop' | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment