Skip to content

Instantly share code, notes, and snippets.

@ljmocic
Created September 2, 2019 13:08
Show Gist options
  • Save ljmocic/a12a0c9f076d7499adce2d0d62bcf931 to your computer and use it in GitHub Desktop.
Save ljmocic/a12a0c9f076d7499adce2d0d62bcf931 to your computer and use it in GitHub Desktop.
import os
import json
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
def detect_event(event):
if event['detail']['eventName'] == 'CreateRole' and event['detail']['responseElements'] != None:
return role_creation_event_allowed(event)
if event['detail']['eventName'] == 'CreateRole' and event['detail']['errorCode'] != 'AccessDenied':
return role_creation_event_disallowed(event)
if event['detail']['eventName'] == 'DeleteRole':
return role_deletion_event(event)
return fail_response('failed to detect an event')
def role_creation_event_allowed(event):
# create row in the database
if len(event['detail']['responseElements']['role']['tags']) != 0:
item = {
'RoleName': event['detail']['responseElements']['role']['roleName'],
'RoleArn': event['detail']['responseElements']['role']['arn'],
'AccountId': event['detail']['userIdentity']['principalId'],
'Department': event['detail']['responseElements']['role']['tags'][1]['value'],
'Description': event['detail']['requestParameters']['description'],
'Owner': event['detail']['responseElements']['role']['tags'][0]['value'],
'Tag': event['detail']['responseElements']['role']['tags'][3]['value'],
'Roletype': event['detail']['responseElements']['role']['tags'][2]['value'],
}
else:
item = {
'RoleName': event['detail']['responseElements']['role']['roleName'],
'RoleArn': event['detail']['responseElements']['role']['arn'],
'AccountId': event['detail']['userIdentity']['principalId'],
'Department': 'null',
'Description': event['detail']['requestParameters']['description'],
'Owner': 'null',
'Tag': 'null',
'Roletype': 'null',
}
table.put_item(Item=item)
return success_response('created row')
def role_creation_event_disallowed():
return fail_response()
def role_deletion_event(event):
print(event['detail']['requestParameters']['roleName'])
table.delete_item(
Key={
'RoleName': event['detail']['requestParameters']['roleName']
}
)
return success_response('Deleted row')
def lambda_handler(event, context):
return detect_event(event)
def success_response(message):
return {
'statusCode': 200,
'body': json.dumps(message)
}
def fail_response(message):
return {
'statusCode': 500,
'body': json.dumps(message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment