This post is part of my “Serverless” series. In this part, I will show you how to setup a Lambda function to send mails on a defined scheduled event from CloudWatch.
1 – Create Lambda Function
So start by cloning the project :
1 | git clone https://github.com/mlabouardy/schedule-mail-lambda.git |
I implemented a simple Lambda function in NodeJS to send an email using MailGun library
1 | 'use strict'; |
Note: you could use another service like AWS SES or your own SMTP server
Then, create a zip file:
Next, we need to create an Execution Role for our function:
1 | { |
1 | aws iam create-role --role-name lambda_execution --assume-role-policy-document file://lambda_role_policy.json |
Execute the following Lambda CLI command to create a Lambda function. We need to provide the zip file, IAM role ARN we created earlier & set MAILGUN_API_KEY and MAILGUN_DOMAIN as parameters.
1 | aws lambda create-function --region us-east-1 --function-name mail-scheduler \ |
Note: the –runtime parameter uses Node.JS 6.10 but you can also specify Node.JS 4.3
Once created, AWS Lambda returns function configuration information as shown in the following example:
Now if we go back to AWS Lambda Dashboard we should see our function has been successfuly created:
2 – Configure a CloudWatch Rule
Create a new rule which will trigger our lambda function each 5 minutes:
Note: you can specify the value as a rate or in the cron expression format. All schedules use the UTC time zone, and the minimum precision for schedules is one minute
If you go back now to the Lambda Function Console and navigate to the Trigger tab, you should see the CloudWatch has been added:
After 5 minutes, CloudWatch will trigger the Lambda Function and you should get an email notification:
Drop your comments, feedback, or suggestions below — or connect with me directly on Twitter @mlabouardy.