Sunday 8 January 2017

AWS Lambda: Go Serverless and Run only the Code

ServerLess Computing with AWS Lambda Service

AWS Lambda, Run Code without Servers

Getting Started with AWS Lambda

What is it?

AWS Lambda is a computing service of Amazon Web Services that lets you run the code directly, without any need of provisioning and supervising the servers. The interesting thing about this service is, you need to pay for the time, your code runs. There is no charge for the time, when the code is idle. Lambda is capable to run code for virtually any kind of application, without any need of management or administration. Lambda administer for everything required to run or scale your code, for high availability of your application. You just need to deploy your code, Interesting! You can configure your code, to call it from other AWS service, any or Mobile application.

How is it possible? The Container Model

While creating Lambda function, you need to specify some configuration information like amount of memory, maximum execution time etc for your application. When a Lambda function get called, AWS Lambda launches a execution environment that is a Container based on the configuration information you provided. It takes time to set up a container and do the necessary bootstrapping, which adds some latency each time the Lambda function is invoked. But this latency is significant only for the first time, when a Lambda function gets call or when its get updated. Reason behind this is, AWS Lambda tries to reuse the container for subsequent invocations of the Lambda function.

When a Lambda function gets execute, AWS Lambda maintains this container for some time in anticipation of another Lambda function invocation. So that it can be reused, when the Lambda function is invoked again.

Advantages of Container Reuse Approach by AWS Lambda

  • All declarations in your Lambda function code (except the main handling code) remains initialised, it provides advantages when the function is invoked again. For example, if your Lambda function establishes a database connection, then instead of reestablishing the connection, the previous connection is used in subsequent invocations.
  • Each container provides some disk space in the /tmp directory . The directory content persist till the container is frozen, that can be used while multiple invocations.
  • If any background processes or callbacks that are initiated by Lambda function did not complete when the function ended, then it can be resumed.
Note: For all above things, you need do write extra code to check whether the conections / content / callbacks / processes are there to server the code in proper way. Else your code can break.

How to use AWS Lambda Service

To use Lambda service of AWS, you need to do below things:
  1. AWS account with administrator access.
  2. AWS CLI (Command Line Interface) setup.
  3. Creation of IAM role (referred as the execution role) with the necessary permissions that AWS Lambda can assume to invoke your Lambda function on your behalf.
  4. Creation of Lambda Function. For this you need to do following things:
  • Selection of Blueprint
  • Configuration of Function
Lets create Hello World Lambda Function

1. So, first sign in to your AWS Account and open AWS Lambda Management Console.


2. Press the Button   Get Started Now  . This button will only appear when you are using this service for the first time. Else you will see the Lambda Function page. On this page, choose the option, Create Lambda function, to redirect on Lambda new function page.

3. On this page, you will get the option for selection of blueprint. Here you can either configure your function from scratch by selecting blank function or can use readymade functions provided by AWS as blueprint.

For this exercise, we will use the readymade function that is hello-world-python blueprint. It provides sample code written in Python 2.7. You are free to create your own Lambda functions in any of the supported languages or choose any other blueprint.


Note: It may happen that hello-world-python blueprint will not appear on first page of available blueprints. To search for it, click select runtime dropdown and select Python 2.7.  Now in filter option write "hello-world", the required blueprint will be shown.

Blueprint provides example code to do some minimal processing. Most blueprints process events from specific event sources, such as Amazon S3, DynamoDB, or custom application. For example, if you select an s3-get-object blueprint, it provides sample code that processes an object-created event published by Amazon S3 that Lambda receives as parameter.

4. Now, we need to configure the function as per our need. Since we have selected AWS provided Blueprint, the console will have some configuration information pre-populated. For example, it pre-configures Python 2.7 as the runtime, provides example code, identifies the handler in the code sample, and other configuration information such as memory and timeout.


5. After selecting Lambda function, Management Console page will move to Configure triggers page. This page lets you choose the service that can automatically trigger your Lambda function. Click on Grey dotted box, to see available options. This step is optional. Depending on the service you select here, you are prompted to provide relevant information for that service. For example, if you choose DynamoDB service to trigger your Lambda function, then you need to provide the following information:

  • The name of the DynamoDB table
  • Batch Size
  • Starting Position
For this exercise, do not choose any service to trigger and click   Next   button.

6. Now, you will move to Configure function page. Here you need to review all the preconfigured Lambda function information and edit according to you.

a. Here, first enter the Lambda function name in Name field, for example "hello-world-python".  In Description field, enter the description why you are creating this function. Its optional.

b. Now since we are creating Lambda function in Python, hence make sure that in Runtime dropdown "Python 2.7" is selected.

c. Now review the code, or if you are using custom Lambda function, then enter your code in code editor. If your code uses any custom libraries (other than boto3) then you need to upload your code and custom libraries as .ZIP file. For this you need to click Code entry type dropdown and select option upload a .ZIP file.


For this exercise, we are not going to use any custom library, hence we will use code editor only and will not required to upload any .ZIP file. Now see the hello-world-python code. There is a lambda_handler function that receives the event as a parameter when the Lambda function is invoked. The sample code processes incoming events of the following form:


{
"key3": "value3", 
"key2": "value2",
"key1": "value1"
}

NoteThe console saves this code as lambda_handler.py. The console then zips the file, and uploads it to AWS Lambda creating your Lambda function.


d. Now, in Environment variables section, you can pass key and values for environment variable, if your code requires it. For this exercise, leave it empty.


e. In the Lambda function handler and role section,  
  1. First note the Handler* value. It generally has the form python-file-name.handler-function.
  2. In Role* dropdown section, choose Create new role from template(s). Then in Role name*, type the name of the role, you want to create. For example, hello-world-role.
  3. In Policy templates dropdown section, Lambda provides a list of optional templates from which you select one. It automatically creates the role with the requisite permissions attached to that policy. For this exercise, you can leave this field blank because your Lambda function already has the basic execution permission it needs.

    NoteOptionally, you could select Choose an existing role if you already have a role created with specific permissions beyond basic execution. You can also select Create a custom role. When you choose this option, a window appears where you can edit the permissions policy inline.
f. In the Advanced settings section, leave the default Lambda function configuration values. In this section, you need to configure memory and timeout values sufficient for the Lambda function you are creating. These configurations influence the performance of your code. For this exercise, default values are enough.

g. Keep other remaining information as it is and click  Next   button.

h. Now review the the Lambda information once more and click  Create Function  to create a Lambda function. Now your Lambda function got created successfully.

Note the tabs in the console:

  • Code – It shows the Lambda function code.
  • Configuration – shows current function configuration and you can change the configuration as needed. After you change any configuration settings, you choose Save to save the updated configuration.
  • Triggers – Shows any triggers you configured for this function (does not apply for this exercise).
  • Monitoring – Provides various CloudWatch metrics for your Lambda function. In the next section, you invoke your hello-world-python Lambda function and review these metrics.

Congrats! Lambda Function creation work completes here. If you want to test, your created Lambda Function manually and want to verify results, logs and metrics then follow the below section.

Lets test newly created Lambda function

To test the Lambda function you need to invoke it using the sample event data provided in the console. For this do:
  • On the Lambda > Functions > HelloWorld page, click   Test   button.
  • In the Input test event page, choose Hello World from the Sample event template list. The following sample event template appears in the window.
  1. {
     "key3": "value3", 
     "key2": "value2", 
     "key1": "value1" 
    }
  2. NoteYou can change key and values in the sample JSON, but don't change the event structure. If you do change any keys and values, you must update the sample code accordingly. Choose Save and test.
  3. Now, AWS Lambda executes your Lambda function on your behalf. The handler in your Lambda function receives and processes the sample event.
  4. After successful execution, view results in the console.

Note below points to understand the result:

  • The Execution result section shows the execution status as succeeded and also shows the function execution results, returned by the return statement.
  • The Summary section shows the key information reported in the Log output section (the REPORT line in the execution log).
  • The Log output section shows the log AWS Lambda generates for each execution. These are the logs written to CloudWatch by the Lambda function. The AWS Lambda console shows these logs for your convenience.

You have tested the Lambda Function successfully.

1 comments:

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel