Thursday, December 19, 2019

AWS Lambda Functions

Create Lambda function

Go to AWS Lambda homepage and login to console.
Press "Create Function" button.
Enter function name.
Select a language (environment) from Runtime dropdown. I will use node.js 8.10.
For the first time you can create a new role for permissions. Select "Create a custom role" from Role dropdown box.
A new page will be shown. Select "Create a new IAM Role" from IMA Role dropdown and then give a name. Press "Allow" button.
This will create a new role and browser will return back to "Create function" page.
Press "Create function" button.
It will redirect you to function page.
Initially the page adds a template code which returns success code and a hello message. We will continue with this code.
 

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

2. AWS CLI to call the function

Download AWS CLI setup to your computer. For Windows download link is here. For other operating systems you can find links at the same page.
After installation go to aws cli folder and run following command to start configuration.
aws configure
We need following info.
AWS Access Key ID [None]: "Your Access Key"
AWS Secret Access Key [None]: "Your Secret Key"
Default region name [None]: 
Default output format [None]: 
To get keys go to AWS console
Click to your name and select "My Security Credentials".
On "Access keys" section click to "Create New Access Key" button to create new keys. You have to save your secret key because it will displayed only once.
Now return back to aws cli console and enter Access Key ID and Secret Access Key.
Enter region name like "us-west-2".
Enter json for default output format.
Now you can run your functions.
We need our function name as a parameter. In lambda function page copy arn.
Run aws command to run function. The lines between "{ }" is the response from our lambda function. You can see hello message inside txt file which we passed as a parameter.
aws lambda invoke --function-name arn:aws:lambda:us-west-2:123456780315:function:FirstLambda "c:\aws.txt"

{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
aws.txt file content
{"statusCode":200,"body":"\"Hello from Lambda!\""}