How to periodically call a Lambda function

(Read this article on the blog)

Timing events

Serverless architectures are event-driven, things start processing when there is something that triggers them. This makes it great to react to an API call, a
new object in an S3 bucket, or a notification coming in a queue. But for scheduled tasks, such as triggering a daily backup or generating an aggregated seasonal
report, Lambda needs a separate service to provide the events.

Fortunately, AWS offers such a service: the CloudWatch Event Rules. You can configure one to periodially call a Lambda function, among other potential event
targets. It supports relative timing (run every 10 minutes) as well as
absolute ones (run everyday at 3 a.m.). For the latter, it supports the CRON syntax, making it familiar to sysadmins.

This Event Rule is configured to run every minute (rate(1 minute)) and it calls the function with the ARN on the third column:

Permissions

As a general pattern in AWS, services need permissions to call each other. This is usually done using a role that the caller uses, but CloudWatch Event Rule
targets don’t support this pattern (even if there is a role argument, it does not work for Lambda).

For these cases, AWS supports a different mechanism: resource-based permissions.

Here, the Lambda function defines a permission that allows the events.amazonaws.com service to call it:

By itself, it would open the door for all Event Rules, so use the AWS:SourceArn condition to restrict it to this specific target:

{
	"ArnLike": {
		"AWS:SourceArn": "arn:aws:events:<region>:<account>:rule/<rulename>"
	}
}

Testing

The Lambda is called every minute:

Source: Advanced Web Machinery

Leave a Reply

Your email address will not be published.


*