Created
February 5, 2020 17:54
-
-
Save jtroberts83/53c082585af3fc1aeec1b3effe762326 to your computer and use it in GitHub Desktop.
AWS Lambda function code (python 3.6) which reads in a Cloud Custodian message, parses the fields and sends to a DynamoDB table
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 json | |
import boto3 | |
import random | |
def lambda_handler(event, context): | |
dynamodb = boto3.client('dynamodb') | |
Records = event['Records'] | |
print(json.dumps(event)) | |
for Record in Records: | |
Message = Record['Sns']['Message'] | |
Timestamp = Record['Sns']['Timestamp'] | |
Subject = Record['Sns']['Subject'] | |
MessageId = Record['Sns']['MessageId'] | |
HTMLTable = ((Message.split(' <table style='))[1]).split('</table>')[0] | |
HTMLTable = "<table style=" + HTMLTable + "\n</table>" | |
MessageSplit = (Message).split('\n') | |
counter = 0 | |
for line in MessageSplit: | |
counter = (counter + 1) | |
#print(line) | |
if 'AWS ACCOUNT NAME' in line: | |
#print(line) | |
AccountName = ((((MessageSplit[counter]).split('>'))[1]).split('<'))[0] | |
AccountNumber = ((((MessageSplit[counter + 4]).split('>'))[1]).split('<'))[0] | |
PolicyRegion = ((((MessageSplit[counter + 8]).split('>'))[1]).split('<'))[0] | |
PolicyName = ((((MessageSplit[counter + 12]).split('>'))[1]).split('<'))[0] | |
ResourceType = ((PolicyName.split('-'))[1]).upper() | |
if 'HIGH' in ResourceType: | |
ResourceType = "SECURITY GROUP" | |
print(ResourceType) | |
print(AccountName) | |
print(AccountNumber) | |
print(PolicyRegion) | |
print(PolicyName) | |
if 'VIOLATION DESCRIPTION' in line: | |
ViolationDescription = ((((MessageSplit[counter]).split('>'))[1]).split('<'))[0] | |
print(ViolationDescription) | |
if 'ACTION DESCRIPTION' in line: | |
ActionDescription = ((((MessageSplit[counter]).split('>'))[1]).split('<'))[0] | |
print(ActionDescription) | |
print(HTMLTable) | |
print(Timestamp) | |
EntryId = random.randint(1, 99999999999999999999999) | |
EntryId = str(EntryId) | |
print(EntryId) | |
dynamodb.put_item(TableName='OUR_Custodian_Affected_Resources', Item={'Id':{'S':EntryId},'AccountName':{'S':AccountName},'AccountNumber':{'S':AccountNumber},'PolicyRegion':{'S':PolicyRegion},'PolicyName':{'S':PolicyName},'ViolationDescription':{'S':ViolationDescription},'ActionDescription':{'S':ActionDescription},'HTMLTable':{'S':HTMLTable},'Timestamp':{'S':Timestamp},'ResourceType':{'S':ResourceType},'Subject':{'S':Subject},'MessageId':{'S':MessageId}}) | |
print('################################################################## WROTE TO DB ####################################################################################') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment