Saturday, August 10, 2019

Run AWS Lambda Function Code Locally - Quick Tutorial

Why do I want to Run the Lambda Function Code locally?


One of my dev friends falsely believed that AWS Lambda Function would require deployment in order to run. This is not true. It is a common misunderstanding since in the Lambda Function you are only defining a handler.

The solution is simple - just write a main function that includes your lambda handler and pass parameters to it! No deployment needed.

How to Do it?


Here's your lambda function in index.js

exports.handler = (event, context, callback) => {
  console.log('hello', event.name, 'from', process.env.SERVICE_NAME);
  callback(undefined, 'done');
};
Write your main.js

process.env.SERVICE_NAME = 'commandline lambda function';

const index = require('./index.js');

const context = {};

const event = {
  "name": "world"
}

index.handler(event, context, (err, data) => {
  if (err) { console.error('error: ', err); }
  if (data) { console.log('data: ', data); }
});
You have environment variables defined, have your event defined, and invoked the lambda function handler. Now just call it from the terminal:
node main.js
Note that it will use the credential in your ~/.aws/credentials file, just like the aws-cli tool.

How to run the command line lambda function with aws-okta credentials:

aws-okta exec my-aws-account-name -- node main.js

No comments: