AWS Lambda-Canary Node Js

The Scenario

I am learning about AWS Lambda functions and doing a small tutorial that works through using the lambda-canary blueprint which uses python 2.7

The Problem

I want to do this same canary function in Node.js 6.10, but I could not find out how to do this.

The solution

Below is the code sample that I came up with to implement the lambda-canary-nodejs lambda function

[csharp]
var http = require(‘http’);

exports.handler = (event, context, callback) => {

var site = process.env[‘site’];
var expected = process.env[‘expected’];

console.log(‘Checking website: ‘ + site);

http.get(site, (resp) => {
let body = ”;

// read the data
resp.on(‘data’, (chunk) => {body += chunk; });

// The whole response has been received.
resp.on(‘end’, () => {
// validate that the expected value is in the returned stream
if(body.indexOf(expected) > 0){
console.log(‘website is up’)
callback(null, event[‘time’]);
} else {
console.log(‘website did not respond as expected’)
var error = new Error(‘website did not respond as expected’);
callback(error);
}
});

}).on("error", (err) => {
console.log("Error: " + err.message);
callback(err);
});

};
[/csharp]

Items to note about this code:

  1. process.env[‘key’] is how you access the environment varialbes/li>
  2. environment variables are case sensitive, so the string index must match variable name as defined on the lambda function
  3. callback accepts an error object as the first parameter when it fails

So to implement this you would:

  1. Create a new blank function
  2. Past in this code
  3. Setup 2 x environment variables, site & expected
  4. Create a test of type scheduled event
  5. Test the code

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.