How to set up Lambda on amazon using Python

What is AWS Lambda?

 AWS Lambda is an event-driven computing cloud service from Amazon Web services. It allows developers to program functions without being concerned about provisioning resources or computing resources. With AWS Lambda, Amazon manages the servers allowing the developers to focus on writing application code. AWS Lambda allows you to create Lambda functions in the following languages

Node.js, Java, C#, Go, Python.

 

With AWS Lambda, you are not charged when your code is not running. You only pay for your computing time.

You can set up your AWS Lambda code to automatically trigger from other AWS services or call it directly from any web or mobile app. For instance, developers can use AWS Lambda to code and run functions in response to specific events such as object uploads to Amazon S3 buckets, Updates to Amazon Dynamo DB tables, or an Mobile app activity.

 

Steps to set up LAMBDA On Amazon using Python :

You can follow these steps to create and run a simple Lambda function on Amazon.

 

Step 1: Sign in to the AWS management console and open the AWS Lambda console.

 

Step 2: Under the Services tab, Click on Lamda under the Compute section. This will take you to the Functions page which displays Lambda functions which are already created.

Step 3: In this page, click on Create Function button which will take you to Create Function page where you can create Lambda functions.

Create Function Page :

This page will give you three options

  • Author from scratch: This option allows you to create a Lambda function from scratch by providing basic information such as function name, preferred runtime, and role.

 

  • Blueprints: This option allows you to create Lambda Functions from a blueprint i.e a simple
    getting started template preconfigured with event source and code.
  • Serverless application repository: This option allows you to find and deploy serverless apps published by developers, companies, and partners on AWS.

 

In this article, we will focus on creating Lambda functions from scratch and from blueprints.

 

Step 4: Author from scratch :

 

In this page do the following to create a Lambda function from scratch:

 

  • In Name specify your Lambda function name.
  • In Runtime choose the language in which you want to create a Lambda function. In this case, choose Python 3.6.
  • The Roles section allows you to define permissions for your function. This section allows you to choose from 3 options I.e

Choose an existing role: This option allows you to choose a role from existing roles.

Create new role from templates or: This option allows you to create a role with permissions
from the selected policy templates.

create a custom role: This option allows you to create a custom role with permissions.

In this case, choose from an existing Role.
Click on Create Function button to create a function. Once the function is created, you will be taken to a page where success message is displayed.

This page also contains the following sections.
Configuration: This section allows you to change the configuration of the Lambda function that you have created.

 

The Configuration section contains the following subsections :


Designer:
T his subsection contains the Add Trigger panel which allows you to optionally choose a service that automatically triggers your Lambda function by choosing one of the service options listed.

 

Depending upon the service you select, you need to provide relevant information about the service.
For e.g If you select DynamoDB, you need to provide the following :

  • The name of Dynamo DB table
  • Batch size
  • Starting position

For this example, you need not configure a trigger.

 

Function Code: This subsection allows you to provide your code for the Lambda function.

 

The code entry type option in this subsection allows you to either edit your code inline, or upload you code from a zip file or, or upload a file from Amazon S3.
In this case, choose the option to edit your code inline.

 

The following AWS Lambda function code returns the square value of all the numbers contained inside the list l.
The code is as follows :

lambda_function.py :

[sourcecode language=”plain”]

def lambda_handler(event, context):

# TODO implement

l=[1,2,3,4,5]

result = [i**2 for i in l]

return result

[/sourcecode]

 

 

The Runtime option in this subsection allows you to choose your language for the code for your Lambda function. In this case, choose Python 3.6.

 

The Handler option allows you to specify a handler for your Lambda function.
AWS Lambda invokes your Lambda function via a handler object. A handler serves as an entry point that AWS Lambda uses to execute your function code.

 

For e.g, the handler in this case lambda_function.lambda_handler would call lambda_handler in lambda_function.py.

 

In the syntax of the handler function, note the following
event: This parameter is used by AWS Lambda to pass event data to the handler.

context: This parameter is used by AWS Lambda to pass runtime information to the handler.

 

Environment variables: This subsection allows you to define environment variables.

Environment variables are key-value pairs that are accessible from your function code.
They allow you to dynamically pass settings to your function code and libraries without making changes to your code.

You can use environment variables to help libraries know what directory to install files in, where to store outputs, store connection and logging settings, and more.
In this case, you can leave this section blank.

Tags: Tags are used to group and filter your functions. A tag consists of a case sensitive key value pair

They are particularly useful when you have resources of the same type, which in case of AWS Lambda, is a function. By using tags, customers with hundreds of Lambda functions can easily access and analyze a specific set by filtering on those that contain the same tag.

 

In this case, you can leave the section blank.

 

Execution role: Execution roles allow you to provide security for your Lambda function using defined roles and policies or creating new ones.
In this case, you can choose from an existing role.

 

Basic settings: Basic settings allow you to provide memory allocation and timeout limit for your Lambda function. These settings allow you to control the code execution performance and costs for your Lambda function. Changing your resource settings by selecting memory or changing timeout may impact your function cost.

 

Network: Network allows you to select a VPC(Virtual Private Cloud ) your function will access.

All AWS Lambda functions run securely inside a default system managed VPC. However, you can optionally configure Lambda to access resources, such as databases, within a custom VPC. To enable Lambda functions to access resources inside your private VPC, you must provide additional VPC specific configuration information that includes VPC Subnet Id’s and security group id’s .

In this case, you can choose No VPC.

Debugging and Error Handling :

AWS Lambda automatically retries failed executions for asynchronous invocations. Additionally, you can also configure AWS Lambda to forward payloads that were not processed to dead letter queues such as SQS Queue or SNS topic.

It also allows you to enable active tracing. When this option is checked Lambda will attempt to trace your function. If it is unchecked, your function will be traced if it is explicitly told to do so by an upstream service.

 

In this case, select None for DLQ resource and disable active tracing.

Concurrency: This option allows you to set the concurrency limit for your Lambda function.

You can specify a numerical value for concurrency by using the reserve concurrency option. If you specify a value, it has two effects

  • It limits the number of instances of your Lambda function that can be instantiated at any time to the value specified. In the screenshot, I have specified that the reserved concurrency for my function is 20. This means that at most 20 instances of my Lambda will run at any given time.
  • It also makes sure that there is at least enough concurrency capability available in the account to run the number of instances requested. Since I have specified the value as 20, it means that of my account wide concurrency limit (which defaults to 1000), 20 units worth will b available for this function. If 20 instances need to run then Lambda function will be able to do so, no matter what else is going in our account.

Auditing and compliance :

 

This feature logs function invocations for operational and risk auditing, governance, and compliance.
The AWS Cloudtrail feature allows you to view events for your AWS account. You can create a trail to retain a  record of the events. With a trail, you can also create event metrics, trigger alerts, and create event workflows.

 

To get started, visit Cloudtrail console.

Monitoring: You can choose the Monitoring tab to view the Cloudwatch metrics for your Lambda function.

Step 5: Invoke the Lambda function manually :

 

Choose the drop-down value “Configure test events ” just adjoining the Test button.

This will take you to the Configure test event page. In this page, you can create test events by either creating a new test event or editing a saved test event. A Lambda function can have up to 10 test events.

 

In this page choose to Create new test event and in the event template leave the default Hello World option. Enter an Event Name and note the following sample event template.

[sourcecode language=”plain”]

{

"key3": "value3",

"key2": "value2",

"key1": "value1"

}
[/sourcecode]

You can change key and values in the sample JSON, but don’t change the event structure.I f you change any key and values, you will have to change the sample code accordingly.

 

Click on Create button to create an event. Now choose the event and Click on Test to test your Lambda function.

Once it is successfully executed you can view the results in the console.

As explained above, you can choose the Monitoring tab to view the Cloudwatch metrics for your Lambda function.

 

Step 6: Blueprints :

In the above example, we have seen how we can create AWS Lambda function from scratch. We will now take a look at how we could create a Lambda function from blueprint I.e a simple getting started a template preconfigured with the event source and code.
Choose Blueprints from the create function page. Use the filter box to find blueprints by name, keyword, runtime or tags.
Choose a blueprint from the results and click on it. It will take you to a page where you can configure the Lambda function further.

Enter Name for your Lambda function.
In the role section, you can choose from the following options

choose an existing role, create a new role from the template or Create a custom role.

You can select choose an existing role .and select a role from the given options.

 

The lambda function code of the blueprint is displayed ion the code window. The code is preconfigured with the chosen blueprint. You can configure it after you create the function.

 

Click on Create function button to create the Lambda function.

If the function is successfully created a success message is displayed.

Just as you have created test events for Lambda function created from scratch, you can configure a  test event for a Lambda function created from a blueprint.

You can choose the configure test event from the drop-down. This allows you to choose an option to either Create a new test event or Edit a saved test event.

For this example, you can choose to create a new test event.

 

Enter the name of the event, leave the event template as is, and click on Create button to create a new test event.

 

Finally, click on Test button to test your Lambda function created from a blueprint.

You can choose the Monitoring tab to view the Cloudwatch metrics for your Lambda function.

 

Subscribe Us