Easy Way to Create an AWS Lambda Function

Easy Way to Create an AWS Lambda Function


aws-lambda



Goal:

 - Function will list all items inside an S3 Bucket
 - Should be able to be triggered via API


What we'll have in the end:

  1. A Lambda User Role - which will run the lambda function, preferably with S3 read-only permission.
  2. A NodeJS function - which will be the logic of the function.
  3. A JSON test input - which will be put to the function for testing purposes.




Prerequisites:

  1. A Public S3 Bucket. How to make my S3 Bucket Public?

Author a Function from Scratch

  1. Click the Create Function button
  2. Name your function
  3. Choose your Runtime
  4. Create new Role from Template
  5. Name your Role
  6. Choose a policy for your role.
  7. So choose the "S3 Object read-only permission" from the Policy templates.
  8. Click Create, and we will proceed to the IDE itself.
author-from-scratch
Author from Scratch




IDE

One of the things that is important in the code is the callback() function.
The Callback function needs 2 parameters, the Error Response and the Success Response.

To use the callback as a success callback, you just need to put NULL on the 1st parameter and put your output to the 2nd.

callback(null,{status:true,message:'something succeeded'});

To use it as an error callback, you just NULL out the 2nd parameter.

callback('Something went wrong',null);

Without this callback function, the return of the function will just be NULL.

NOTE:
You may also use the context.done() function instead of the callback() function.
But to make things simple, we'll stick to the default.




Sample Code: Listing S3 Objects.

In AWS Lambda, you can just require() libraries on the fly.
For this example, we'll require AWS SDK using require('aws-sdk')
Now we can use the AWS SDK in our function.

Event.queryStringParameters - These are the query string parameters via the GET request in the URL for example: https://www.domain.com?someKey=someValue

 
Event - These are the variables sent via the POST request. for example: {"someKey":"someValue"}

Here, the code tries to get the Bucket and Prefix values from both GET and POST request.





exports.handler = (event, context, callback) => {
    var AWS  = require('aws-sdk');
    var s3 = new AWS.S3();
    var inputObj        = event.queryStringParameters ? event.queryStringParameters : event;
    var Bucket          = inputObj.Bucket    = inputObj.Bucket!==undefined ? inputObj.Bucket : null;
    var Prefix          = inputObj.Prefix    = inputObj.Prefix!==undefined ? inputObj.Prefix : null;
    var params = {
       Prefix,Bucket
    };
    s3.listObjects(params, function(err, data) {
       if (err){
           callback({status:false,message:err},null);
       }else{
           callback(null,{status:true,message:data});
       }    
    });
};


To test this, click the Configure Test Events from the dropdown in the Top Right corner of the page.






configure-test-events
Configure Test Events


And since the script just requires 2 variables, we can just put this JSON in the box:
{
    "Bucket": "bucket.domain.com",
    "Prefix": "directoryName"
}

This means we want to list all items in http://bucket.domain.com/directoryName


You can also use the default http://bucket.domain.com.s3-ap-northeast-1.amazonaws.com/directoryName

Save the test configuration, and then Click Test.

The IDE will show a response like this:



Response:
{
  "status": true,
  "message": {
    "IsTruncated": false,
    "Marker": "",
    "Contents": [
      {
        "Key": "directoryName/filename.txt",
        "LastModified": "2018-03-23T14:25:37.000Z",
        "ETag": "\"a5dd7ff87c605a4ba7s8d9f6b98da993\"",
        "Size": 95,
        "StorageClass": "STANDARD",
        "Owner": {
          "DisplayName": "owner123",
          "ID": "7908b0d42ed6c22e1124289711fd9as8f7as 7fa0afd77a0c80085afa3091f"
        }
      }
    ],
    "Name": "bucket.domain.com",
    "Prefix": "directoryName",
    "MaxKeys": 1000,
    "CommonPrefixes": []
  }
}


Now how do we trigger this Function from the outside world?


We'll talk about it in my next Entry: How to Create an AWS API Gateway for AWS Lambda




Comments

Popular posts from this blog

Terraform: Merge a List ofObjects into One

SMS Notification using Gammu on Linux