Articles

Configuring CloudWatch Scheduled Events in the Serverless Framework


In the last article we saw how to execute a AWS Lambda with a scheduled CloudWatch event. Today, we are going to see how to set this up in the serverless.yml file of our services when using the serverless framework.

In the following snippet, you will find our lambda declared in the functions section. Then, the resources section contains the lambda role with its associated policy, and the CloudWatch event with its scheduled defined. Let's see each one of them in detail.

The functions section defines our lambda, and specifies a custom role for our serverless function.

The role can be seen in the resources section for our service. It has a custom policy that allows this lambda to create cloudwatch log groups and streams so we can see its output, and the role allows for the services Lambda (lambda.amazonaws.com) and CloudWatch (events.amazonaws.com) to assume this role and execute the function.

Define a custom Scheduled CloudWatch Event as a Resource in Serverless

Then, in the resources section you will find our CloudWatch Scheduled Event. The syntax is defined in the CloudFormation documentation for Resource Events Rules.

The interesting parts of the event definition are ScheduleExpression, RoleArn, and Targets.

ScheduleExpression is a string that defines when your custom event will be triggered. RoleArn is the role that AWS will use when invoking any targets. The role configured is the Lambda role described earlier, that allows CloudWatch to invoke this function via a trust policy.

Targets include the ARN of your function (discovered via the use of Fn::GetAtt::), and the Input field is a JSON payload that will be sent to your Lambda when the event is triggered.

And that's how you can define custom CloudWatch events in the serverless framework by using the resources section and the YAML syntax of CloudFormation templates.

NOTE: Since I wrote this article, I found out the right way to do this for serverless:

The documentation can be found in the schedule section of the events part of the serverless manual. By just adding the right events section to your lambda configuration this can be achieved in a much more simple way. It's interesting to have this to know how it's written backstage, though :)

Enjoy!