You will require the following AWS permissions:
events:PutRule
lambda:CreateEventSourceMapping
Lambda can listen to various types of CloudWatch events. One of the simplest types of events is CloudWatch Scheduled Event (similar to Cron job).
Just create a serverless.yml
with
service: cloudwatch-event-handler
provider:
name: aws
runtime: nodejs8.10
region: eu-west-1
profile: default
memorySize: 256 # optional, in MB, default is 1024
stage: dev
functions:
signInCloudWatchEvent:
handler: handler.signInCloudWatchEvent
events:
- cloudwatchEvent:
event:
source:
- aws.events
and handler.js
with
module.exports.signInCloudWatchEvent = (event, context, callback) => {
console.log('EVENT', JSON.stringify(event)),
callback(null);
}
After deploying this stack, you can attach this lambda to CloudWatch Event. For example, you can create a new Rule with Schedule of a fixed rate 1 minute in AWS Console. In Targets section set cloudwatch-event-handler-dev-signInCloudWatchEvent
as listening lambda function. After that you should start receiving events on this lambda:
{
"version": "0",
"id": "397c14ce-20b1-cc14-dbca-9deca327fca9",
"detail-type": "Scheduled Event",
"source": "aws.events",
"account": "189075651281",
"time": "2018-06-05T10:48:38Z",
"region": "eu-west-1",
"resources": [
"arn:aws:events:eu-west-1:189075651281:rule/test_rule"
],
"detail": {}
}
Now, you can listen to a Scheduler Event from using cron-like CloudWatch functionality. Every time the event is fired, your lambda will be invoked.
Further reading: