Scheduling AWS Lambda Functions by configuring the CloudWatch Events, monitoring through CloudWatch Metrics and CloudWatch Logs.

This blog will provide details on scheduling the AWS Lambda function using CloudWatch Events.

AWS Lambda is a serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers. Lambda executes code on a high-availability compute infrastructure while handling all compute resource management tasks, such as server and operating system upkeep, capacity provisioning and automatic scaling, and logging. We can execute code for practically any kind of application or backend service with Lambda.

AWS resources undergo changes, and Amazon CloudWatch Events provides a stream of system events that is almost real-time. We may match events and rapidly route them to one or more target functions or streams by using straightforward rules. Operational changes are detected by CloudWatch Events as they happen. By delivering messages to respond to the environment, activating functions, making modifications, and capturing state data, CloudWatch Events responds to these operational changes and takes remedial action as appropriate.

As the blog deals with the main concept of CloudWatch Events it has the following concepts and it is important to know about them before proceeding further:

  • Events – A change in our AWS environment is indicated via an event. When an AWS resource’s state changes, events may be produced. For instance, when an EC2 instance transitions from the pending state to the running state, Amazon EC2 generates an event, and Amazon EC2 Auto Scaling generates events when it launches or kills instances. Events are published by AWS CloudTrail when you use its API. Custom application-level events can be created and published to CloudWatch Events.
  • Rules – A rule matches incoming events and sends them to targets for processing. Multiple targets can be routed by a single rule, and they can all be handled concurrently. No particular order is used when processing rules. This makes it possible for various sections of an organization to search for and analyze the events that are relevant to them. By passing only specific bits of the JSON or by overwriting it with a constant, a rule can modify the JSON that is sent to the target.
  • Targets – A target is an event processor. Targets can be built-in targets, AWS Lambda functions, Amazon EC2 instances, Kinesis streams, Amazon ECS tasks, Step Functions state machines, Amazon SNS topics, and Amazon SQS queues. Events are delivered to a target in JSON format.

NOTE: A rule’s targets must be in the same Region as the rule.

In order to create a CloudWatch Event there are three steps to be performed.

  1. Create an AWS Lambda Function.
  2. Create a Rule.
  3. Verify the rule.

1. Create an AWS Lambda Function:

Noting that in order to create an AWS Lambda Function there should be an AWS account and follow the below steps on creating a Lambda Function:-

  • Navigate to https://console.aws.amazon.com/lambda to access the AWS Lambda console.
  • There will be a button on the Lambda Console page at the top right to Create a Function choose that option.
  • On the create function page use a blueprint option and in the text box select one of the blueprint types, hello and there will be values stating Name = hello-world proceed with that.
  • On the configure page give the Function name and for the role select the option Create a new role with basic Lambda permissions.
  • Post creating the function use the below-provided code and deploy, and test the source code.
'use strict';

exports.handler = (event, context, callback) => {
    console.log('LogScheduledEvent');
    console.log('Received event:', JSON.stringify(event, null, 2));
    callback(null, 'Finished');
};
  • The functionality of use strict directive is to signal that the code should be run in “strict mode”.
  • This concludes the first step of creating a Lambda Function. Please find the overview of the created function.

Please don’t worry by considering the EventBridge trigger in the overview as that will be covered in the next step. Now let’s proceed with step 2 i.e Creating a rule.

2. Create a Rule:

Create a rule using the CloudWatch console by following the steps provided:-

  • In the CloudWatch console select the Events at the left panel and go to the Rules option in order to create a rule. As of now the CloudWatch is termed be EventBridge and has more capabilities compared to CloudWatch events such as Integrated SaaS partner event sources, Schema registries, API destinations, and many more.
  • Select the option to Go to Amazon EventBridge and create a rule by opting for the Create rule choice.
  • On the rule create page give the name of the rule and select the option Schedule for the rule type and click on continue to create rule.
  • In the next step to define the schedule pattern give the timeframe for how much time you want to trigger the Lambda Function. I have selected a timeframe of 5 minutes.
  • For the next step to select a target proceed with the AWS Lambda Function and select the Lambda Function which we have created in Step 1 Creating an AWS Lambda Function. In my case, I have given the name as LogScheduledEvent and leave the default values for the configure version and additional settings.
  • For the configure tags leave it as default and proceed to the Create rule step. The final review of the event will be as:
  • Once the event has been created successfully it will be of:

NOTE: Before proceeding to Step 3 please wait for at least five minutes as the trigger to activate the Lambda function because we have given the timeframe as 5 minutes to trigger the function.

3. Verify the Rule:

To check the trigger for the rule created please follow the below steps, there are two ways to verify the rules through the CloudWatch and from the Lambda function logs.

Let’s go through the CloudWatch Metrics for the first verification process:

  • Visit https://console.aws.amazon.com/cloudwatch to access the CloudWatch console.
  • Navigate to the Metrics–>All metrics–>Select the rule that has been created and in the graph, it will notify for the instances that have been triggered from time to time.

For a better understanding, it is advisable to verify through the Lambda function monitor as it provides a brief of logs and to view it in cloudwatch logs through the Lambda function console. Please follow the mentioned steps to understand the logs of the triggered events.

  • In order to check the Logs for the triggered event we can select the option View logs in CloudWatch or from the LogStream as well.
  • For the latest invocation, I have selected from LogStream and it will be navigated to the CloudWatch logs panel.
  • Another course of action to verify the rule logs is directly from the CloudWatch Logs panel which provides the same set of logs that has occurred in the Lambda function monitor tab.
Multiple log entries for Function for every 5 minutes from CloudWatch logs

Disable the Rule:

Once the rule has been triggered and verified it is a good practice to disable the rule in order to reduce the pricing. Please follow the steps to disable the rule:-

  • A dialog prompt will appear to confirm the disable process of the rule, click Disable.
  • Once the rule has been the disabled status of the rule will be changed from enabled to disabled.

Please refer to the link which provides the full pricing charges of the Amazon CloudWatch events metrics and logs https://aws.amazon.com/cloudwatch/pricing/

Thanks for reading the blog!!