Lambda functions can be triggered based on the events either synchronously and asynchronously.
In this guide, We will learn how to trigger lambda functions using the Cloudwatch events.
If you’re new to the lambda function And Want to know more about Lambda function and How to Create Lambda function using AWS Console.
Invoking Lambda Functions
AWS Lambda functions can be invoked directly using the AWS Console, AWS CLI, AWS SDK, and Lambda API. It can also be invoked by other AWS services.
Setup Cloudwatch Event Rule
Let's create a cloud watch event rule to invoke the lambda functions.
Login to Cloudwatch Console, In the left panel, Under Events, Choose Rules
Click Create rule, For the Event Source, Choose Schedule.
We are going to trigger the lambda function based on the Schedule by configuring the Cron expression.
You can either trigger the lambda function for the fixed rate of ’n’ minutes.
Or You can configure specific Cron expression. For example , Everyday at 1 AM (0 1 * * *)
Next, We have to add the Lambda function as a Target to this Event Rule.
Under Targets, Click Add target, In the drop-down menu, choose the Lambda function, For Function, Choose the function name.
If you want to trigger multiple lambda functions at the same time using the same Event Rule, You can add targets here.
Choose Configure details, Under the Rule definition, Specify a name for the rule with a short description.
Make sure that the State is Enabled.
Cloudwatch Events will automatically add the necessary permissions to trigger the lambda functions.
Verifying the Cloudwatch Event Rule
To verify whether the configured rule is working as expected, Go to Cloudwatch Console
Under Events, Choose Rules, Select the created rule,
In Monitoring, Click Show metric for the rule, You should see the metrics graph for the rule as per the con expression.
Alternatively, You can also check the output of the Lambda function using the Cloudwatch Logs
Whenever the lambda function is invoked It outputs the results to the lambda function for any messages or errors.
From the Cloudwatch Console, Choose Logs, Click Log group
You can search for the Log group for that lambda function as shown below,
Inside you can see the lists of streams created for all the lambda executions.
Click the Latest stream to check the response of the lambda function.