AWS Classroom Series – 26/Jun/2020

AWS Lambda Programming Model

  • Common Programming model is defined as interface between code and the runtime. You can tell runtime which method to run by defining a handler in the function configuration. Runtime passes in objects to the handler that contain the invocation event and the context
  • Lets Build a function in python. Giving the Permissions to AWS services/resources is called as role.
  • Lets create a role for aws lambda function Preview Preview Preview Preview
  • Now lets navigate to AWS Lambda console and create a function Preview Preview Preview
  • Now navigate to the function code and observe the handler, event and context Preview
  • For more info on handler Refer Here
  • For more info on context Refer Here
  • Lets create a basic function with the following code
import json

def lambda_handler(event, context):
    new_line = "\n"
    message = "Event info {} {} ".format(event,new_line)
    print("Log stream name:", context.log_stream_name)
    print("Log group name:",  context.log_group_name)
    print("Request ID:",context.aws_request_id)
    print("Mem. limits(MB):", context.memory_limit_in_mb)
    # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
    time.sleep(1) 
    print("Time remaining (MS):", context.get_remaining_time_in_millis())
    return {
        'statusCode': 200,
        'body': json.dumps(message)
    }

  • Now to test this function lets configure test event Preview Preview
  • Now lets test the function Preview Preview

Sample: Lets write a lambda function to fetch all the s3 buckets

  • Create an IAM Role lambdas3 with permissions on S3 bucket and the sample code is
import json
import boto3

def lambda_handler(event, context):
    s3_my_client = boto3.client('s3')
    buckets_list = s3_my_client.list_buckets()
    buckets = []
    for bucket  in buckets_list['Buckets']:
        print(bucket['Name'])
        buckets.append(bucket['Name'])
        
    return {
        'statusCode': 200,
        'body': json.dumps(buckets)
    }

Lets try the similar stuff in Nodejs

  • Try using the following code
exports.handler = async (event, context) => {
    var new_line = "\n";
    var message = "Event info "+event+ new_line;
    console.log("Log stream name:", context.log_stream_name);
    
    
    const response = {
        statusCode: 200,
        body: JSON.stringify(message),
    };
    return response;
};

Leave a Reply

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

About learningthoughtsadmin