Last active
September 21, 2021 17:57
-
-
Save kdclaw3/dbac5aa8890ec4238d717b0c0c3c481d to your computer and use it in GitHub Desktop.
Amazon Monitron Lamda Function
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
// Amazon Monitron Lamda Function | |
// Basic Example grabbing info from S3 Bicket | |
const aws = require('aws-sdk'); | |
const s3 = new aws.S3({ apiVersion: '2006-03-01' }); | |
var ses = new aws.SES({ region: "us-east-1" }); | |
const prefix = '[LOGPREFIX] ' | |
exports.handler = async (event, context) => { | |
// Get the object from the event and show its content type | |
const bucket = event.Records[0].s3.bucket.name || 'bucket_name_default'; | |
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); | |
const s3Params = { | |
Bucket: bucket, | |
Key: key, | |
}; | |
try { | |
// grab the content type and raw monitron body | |
const { ContentType, Body } = await s3.getObject(s3Params).promise(); | |
if (ContentType === 'application/json') { | |
let monitronData = Body.toString('utf-8'); | |
monitronData = JSON.parse(monitronData); | |
const subject = [monitronData.assetState.newState, monitronData.assetDisplayName, monitronData.sensorPositionDisplayName].join(String.fromCharCode(32)); | |
const body = JSON.stringify(monitronData); | |
const emailParams = { | |
Destination: { | |
ToAddresses: ['[email protected]'], | |
}, | |
Message: { | |
Body: { | |
Text: { Data: body }, | |
}, | |
Subject: { Data: subject }, | |
}, | |
Source: '[email protected]', | |
}; | |
return ses.sendEmail(emailParams).promise(); | |
} else { | |
return ContentType; | |
} | |
} catch (err) { | |
console.log(err); | |
const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; | |
console.log(prefix, 'ERROR:\n', message); | |
throw new Error(message); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment