We can use the AWS CLI to trigger a Lambda function. Let us create a scenario where we start from scratch and set up a Lambda function.
You firstly create a folder called lambda and create a file with the following code.
console.log('Loading function');
exports.handler = function(event, context) {
var date = new Date().toDateString();
context.succeed("Hello " + event.username +
"! Today's date is " + date);
};
We name this file index.js. The code above simply prints a message with the user's name passed as an event and creates a log with the current date.
Next, we need to assign the Lambda function with a minimal IAM role that AWS Lambda assumes and executes the function with. Therefore, we create a policy called demoPolicy.json containing the following content.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
] }
Let us create an IAM role through the create-role command in the code below.
aws iam create-role
--role-name basic-lambda-role
--assume-role-policy-document file://demoPolicy.json
We have to create a deployment package to upload to an S3 bucket. AWS Lambda will execute this as a function automatically. We use the following code to zip the file and its folder.
zip -r demoFunction.zip index.js
Next, we create our Lambda function through the create-function command.
aws lambda create-function
--region us-west-2
--function-name demoFunction
--zip-file fileb://demoFunction.zip
--role arn:aws:iam::00123456789:role/basic-lambda-role
--handler index.handler
--runtime nodejs4.3
--memory-size 128
We have everything set up now and we can test our function by triggering it through the invoke command from the CLI. The output of the invocation is saved in the output.txt file.
aws lambda invoke
--invocation-type RequestResponse
--function-name demoFunction
--region us-west-2
--log-type Tail
--payload '{"username":"YoYo"}'
output.txt
Note: Commonly asked AWS Lambda interview question