Skip to content

Instantly share code, notes, and snippets.

@made2591
Created March 24, 2018 14:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save made2591/6c4c35590831101f203f8b5b26d4e2f9 to your computer and use it in GitHub Desktop.
Save made2591/6c4c35590831101f203f8b5b26d4e2f9 to your computer and use it in GitHub Desktop.
AWS Lambda Python to handle actions defined in a configuration file over S3
import boto3
import os
import json
##############################################################
###################### Check context #########################
##############################################################
def check_context(event):
if event["context"] in contexts.keys():
return event["context"], True
return "", False
##############################################################
####################### Check action #########################
##############################################################
def check_action(event):
if event["action"] in contexts[event["context"]].keys():
return event["action"], True
return "", False
##############################################################
##################### Check parameters #######################
##############################################################
def check_parameters(event):
if len(event["parameters"]) > 0:
return event["parameters"], True
return [], False
##############################################################
################## Method to execute action ##################
##############################################################
class VPCAction(object):
@staticmethod
def start_instances_action(parameters):
ec2 = boto3.client("ec2", region_name=os.environ["REGION"])
response = ec2.describe_instances(
Filters=[
{
"Name": "tag:Name",
"Values": parameters
}
]
)
instances = [instance["Instances"][0]["InstanceId"] for instance in response["Reservations"]]
response = ec2.start_instances(InstanceIds=instances)
return { "text" : "start instances " + " ".join(p for p in parameters) }
@staticmethod
def stop_instances_action(parameters):
ec2 = boto3.client("ec2", region_name=os.environ["REGION"])
response = ec2.describe_instances(
Filters=[
{
"Name": "tag:Name",
"Values": parameters
}
]
)
instances = [instance["Instances"][0]["InstanceId"] for instance in response["Reservations"]]
response = ec2.stop_instances(InstanceIds=instances)
return { "text" : "stop instances " + " ".join(p for p in parameters) }
@staticmethod
def no_action_defined(parameters):
return { "text" : "no action defined" }
##############################################################
############### Context and allowed contexts ##################
##############################################################
def getActionConfiguration():
s3 = boto3.resource("s3")
content_object = s3.Object(os.environ["S3_BUCKET_NAME"], os.environ["S3_BUCKET_OBJECT"])
file_content = content_object.get()["Body"].read().decode("utf-8")
contexts = json.loads(file_content)
vpcActions = VPCAction()
for context in contexts.keys():
for action_name in contexts[context].keys():
try:
contexts[context][action_name] = getattr(vpcActions, contexts[context][action_name])
except AttributeError:
contexts[context][action_name] = vpcActions.no_action_defined
return contexts
##############################################################
################## Method to execute action ##################
##############################################################
contexts = getActionConfiguration()
def handler(events, cont):
context = ""
action = ""
parameters = []
messages = { "text" : "Nothing to say" }
responses = {}
if isinstance(events, (dict,)) and 'Records' in events.keys():
events = json.loads(events['Records'][0]['Sns']['Message'])
for event in events:
context, context_ok = check_context(event)
if not context_ok:
messages = { "text" : "Invalid context provided"+ event["context"].encode("utf-8") +"'" }
return messages
action, action_ok = check_action(event)
if not action_ok:
messages = { "text" : "Invalid action for provided context: '" + event["action"].encode("utf-8") +"'" }
return messages
parameters, parameters_ok = check_parameters(event)
if not parameters_ok:
messages = { "text" : "Invalid parameters for provided context and action: '" + ' '.join(p for p in event["parameters"]) +"'" }
return messages
responses[event['context']] = contexts[context][action](parameters)
return responses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment