Created
May 20, 2020 20:00
-
-
Save Morrolan/2db22c9e7e42bc3e4db63293de25241b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var aws = require('aws-sdk'); | |
var zlib = require('zlib'); | |
var async = require('async'); | |
var EVENT_SOURCE_TO_TRACK = /sns.amazonaws.com/; | |
var EVENT_NAME_TO_TRACK = /CreateTopic/; | |
var DEFAULT_SNS_REGION = 'us-east-2'; | |
var SNS_TOPIC_ARN = 'arn:aws:sns:us-west-2:123456789012:my-topic'; | |
var s3 = new aws.S3(); | |
var sns = new aws.SNS({ | |
apiVersion: '2010-03-31', | |
region: DEFAULT_SNS_REGION | |
}); | |
exports.handler = function(event, context, callback) { | |
var srcBucket = event.Records[0].s3.bucket.name; | |
var srcKey = event.Records[0].s3.object.key; | |
async.waterfall([ | |
function fetchLogFromS3(next){ | |
console.log('Fetching compressed log from S3...'); | |
s3.getObject({ | |
Bucket: srcBucket, | |
Key: srcKey | |
}, | |
next); | |
}, | |
function uncompressLog(response, next){ | |
console.log("Uncompressing log..."); | |
zlib.gunzip(response.Body, next); | |
}, | |
function publishNotifications(jsonBuffer, next) { | |
console.log('Filtering log...'); | |
var json = jsonBuffer.toString(); | |
console.log('CloudTrail JSON from S3:', json); | |
var records; | |
try { | |
records = JSON.parse(json); | |
} catch (err) { | |
next('Unable to parse CloudTrail JSON: ' + err); | |
return; | |
} | |
var matchingRecords = records | |
.Records | |
.filter(function(record) { | |
return record.eventSource.match(EVENT_SOURCE_TO_TRACK) | |
&& record.eventName.match(EVENT_NAME_TO_TRACK); | |
}); | |
console.log('Publishing ' + matchingRecords.length + ' notification(s) in parallel...'); | |
async.each( | |
matchingRecords, | |
function(record, publishComplete) { | |
console.log('Publishing notification: ', record); | |
sns.publish({ | |
Message: | |
'Alert... SNS topic created: \n TopicARN=' + record.responseElements.topicArn + '\n\n' + | |
JSON.stringify(record), | |
TopicArn: SNS_TOPIC_ARN | |
}, publishComplete); | |
}, | |
next | |
); | |
} | |
], function (err) { | |
if (err) { | |
console.error('Failed to publish notifications: ', err); | |
} else { | |
console.log('Successfully published all notifications.'); | |
} | |
callback(null,"message"); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment