DEV Community

Sharon Wang
Sharon Wang

Posted on

Create AWS Lambda function

Image description
With AWS Lambda, you can run code without needing to provision or maintain servers thanks to serverless computing. You just pay for the computation time that you use. The AWS Lambda interface can be invoked through the AWS command line or the AWS Software Development Kit (SDK) that can run on servers, browsers, and mobile devices.

The first step is to go to https://console.aws.amazon.com/ in the browser in order to access the AWS console. After logging in, click "Get Started Now" on the pop-up page after selecting Lambda in the Compute section and selecting the AWS location from the top menu on the right (typically pick a location closest to your location to minimize network latency). You will see a list of current function codes instead of the welcome page if this is not the first function in the chosen region.Simply select "Create a Lambda Function" in this instance.

The next step is to create lambda functions. Set the option to "Edit code inline" and enter the following code in the web console editor according to your chosen runtime environment. AWS Lambda functions are executed in a environment without any visual information. Therefore, all runtimes implement a convenient way to write centralized logs to Amazon CloudWatch.

Amazon CloudWatch is a monitoring and logging service that can be used to manage application metrics, alerts, and logs, as well as AWS services used within the application.In a Node.js environment, anything written with console.log() is redirected to CloudWatch Logs, whereas in Python, any output from print is redirected.

The following is two instances of the Node.js lambda function.
1.

`//Introducing the core modules required for Lambda
const AWS = require('aws-sdk');

// Function for handling Lambda events
exports.handler = async (event, context,callback) => {
    // return result body
    return {
        statusCode: 200,
        body: JSON.stringify({ message: 'Hello, World!' })
    };
};`
Enter fullscreen mode Exit fullscreen mode

2.

`exports.handler = async (event, context,callback) => {
    console.log('lambda event:', JSON.stringify(event, null, 2));
    var name = '';
    if('name' in event ){
        name = ['name'];
        console.log('name = ', event.name)
    }else{
        name = 'world';
        console.log('name = ', name)
    }
    var result = 'Hi,' + name ;
    callback(null, result);
};`
Enter fullscreen mode Exit fullscreen mode

In Node.js, we use the callback to end functions in the standard Node.js programming model. In this case, the function successfully ends with callback(null, data) and returns the greeting string object. If the first parameter of the callback is not null, it indicates that the function encountered an execution error and returns, such as callback(error).

After initialization is complete, the function receives the information provided as event input and the context of the call—both in their native runtime formats: JavaScript objects in Node.js like https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules_nodejs-sample.html and dictionary types in Python like https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules_python-sample.html, event use case is like this https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules_example-events.html.

The next step is to test function.

Click the Test button in the upper left corner of the console, and then you need to prepare a test event for all the tests. When invoking a Lambda function, the event object information expressed in JSON format will be converted by the actual function runtime into their respective native objects or types, such as JavaScript objects or the Dict type in Python.

The dropdown menu on the test interface contains some sample events, which are received when subscribing to standard resources like Amazon S3 or Amazon DynamoDB. Our function uses a custom format for events, so these sample event templates are temporarily not needed.You need to edit the event information and provide the name as input for the function.

{"name":"Hi, Peter!"}

Click "Save and test" in the window, and the function will be called using the event information you edited as input.The execution results will be displayed at the bottom of the window page. The displayed results include the function's return value, logs, and a summary of the execution status, such as the actual execution time, billing time (in 100 ms units), and memory usage. All this information is also output in the form of raw logs.

If everything goes well, you will see the result in the execution result. Now, you have successfully executed your first Lambda function!

You can also install and configure AWS CLI.

To install and configure the AWS CLI command-line tool, you can refer to the installation guides for Windows, Mac, and Linux provided on the AWS website at http://aws.amazon.com/cli/.

It is recommended to start with the Getting Started link in the documentation to create an AWS IAM user for the CLI.The following is the security policy:

AWSLambdaFullAccess
AmazonAPIGatewayAdministrator
AmazonCognitoPowerUser

When using the aws configure command to set up the CLI, you need to set the current AWS region as the default. Otherwise, you need to explicitly specify the region for each AWS CLI command using the --region option.

At the same time, it is also recommended that you enable the CLI autocompletion feature described in the documentation. To test whether the AWS CLI installation and configuration are correct, you can try executing the command:‘aws lambda list-functions’ to get a list of AWS Lambda functions that have been created under your account, along with the configuration information for each function, such as memory size, timeout, execution role, etc.

The default output format of the CLI is JSON, but it can be changed during the initial configuration of the CLI using the --output option. To invoke the function we just created, use the following syntax in the command line, and the JSON event is in single quotes. If you are using the AWS CLI on Windows to invoke the Lambda function, you need to change the single quotes mentioned above to double quotes and repeat once.

For example, --payload'' should be changed to --payload"{""name"":""Peter""}".

The output of the function is written to a local file. For example, if you want to greet "Peter," enter the following command in the command line. If you did not specify the region where you created and run AWS Lambda when configuring the AWS CLI, you must specify it at the end of the command using the --region parameter; otherwise, the above command will result in an error.

Execute the following command in the command line to test the output of function when no name is provided as input; the returned message will be "Hi, world!"

Top comments (0)