The Lambda function can be configured in response to events. AWS provides a list of triggers that support lots of events. These triggers belong to their associated AWS services.
You can add a trigger to your Lambda function from the triggers section.
I am going to slightly modify the hello world Lambda function. Here, we are printing the request ID, which is received in the context object as an aws_request_id attribute. It also prints the timestamp:
Now, we are going to add a trigger to our Lambda function that will execute our Lambda function every minute.
The following screenshot shows the Add trigger flow, where you can easily configure any trigger from the left-hand panel with your Lambda function:
We are going to configure the CloudWatch Events trigger. CloudWatch Events deliver near real-time system events that describe the changes in AWS resources.
You can set up simple event rules with operational events in AWS resources as they occur, and you can also schedule automated events that self-trigger based on cron or the rate expression.
Here, we are going to schedule a rate expression to execute our hello world Lambda function every minute. We need to select CloudWatch Events from the triggers dropdown.
To create the CloudWatch event rule, we are going to create a new rule. We need to set up the rule with some required information, such as the rule name, which is a unique identifier. So, we are going to name the rule as hello-world-every-minute and the rule type as either the event pattern or schedule expression. In our case, it would be a schedule expression as the rate (1 minute), as shown in the preceding screenshot.
Once we set the trigger and enable it, the scheduled event would get triggered as per the schedule expression. Let's see our hello world Lambda logs after five minutes.
To view the logs related to any services, you need to do the following:
- Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/
- In the navigation pane, choose Logs
- Select the log group related to the HelloWorld Lambda function
The following screenshot describes the CloudWatch log access:
By selecting the HelloWorld Lambda function log groups, you see the logging activity related to our HelloWorld Lambda function. The following screenshot shows the logs of the HelloWorld function:
Here, you can see that our hello world Lambda function is executed exactly every minute since the time we have enabled the trigger.
Now, let's move ahead to create a serverless RESTful API.