Defining A CRON Job to Start Your AWS SAM Lambda
AWS Serverless Application Model (AWS SAM) is an open-source framework that can be used to build serverless applications on AWS. You can define your lambda function using a simple YAML file and upload it to your cloud.
In order to invoke the lambda using a CRON job, you will need to define a CloudWatch Event. The event is defined under the Events
property in the following way:
Resources:
SendMonthlyReport:
Type: AWS::Serverless::Function
Properties:
Handler: monthly_reporter_lambda.handler
Runtime: python3.5
CodeUri: ./
Events:
InvocationLevel:
Type: Schedule
Properties:
Schedule: cron(0 0 1 * ? *)
Here you can see the configuration of the SendMonthlyReport
lambda function. It uses the Python 3.5 runtime and has a scheduled CRON job that will be invoked on the first day of each month.
You can also define the CRON job in the Mapping section of your template, and just refer to it:
Mappings:
prod:
Lambda:
InvocationLevel: cron(0 0 1 * ? *)
staging:
Lambda:
InvocationLevel: cron(0 0 1 1 ? 1970)
Resources:
SendMonthlyReport:
Type: AWS::Serverless::Function
Properties:
Handler: monthly_reporter_lambda.handler
Runtime: python3.5
CodeUri: ./
Events:
InvocationLevel:
Type: Schedule
Properties:
Schedule: !FindInMap [!Ref StackEnv, Lambda, InvocationLevel]
In order to block the Lambda from being invoked automatically in STAGING but still using the mapping option, I defined the dummy CRON job with a past date and invoke it manually whenever needed.
Enjoy!