This repository demonstrates how to use MongoDB Change Streams as a trigger to an AWS Lambda function.
This is the Lambda function used to send an email from a MongoDB Change Stream notification
- In AWS, create an S3 bucket, create a
Templates
folder and upload the ChangeStreamInfo.html file into it. - In AWS, configure SES with (at least) 2 verified email addresses (one will be used to send the email, the other to receive the email)
- In
sam.yaml
, customize- the
S3_BUCKET
environment variable with the value of your S3 bucket - the
FROM_ADDRESS
environment variable with the value of the first SES-verified email address
- the
- In config.js set the
toEmail
property to your other SES-verified email address
- Install SAM Local on your machine
- In the email-lambda folder, run
npm install
to install the required Node dependencies - Run
sh invoke.sh
from Terminal to test your Lambda function local
- Run
sh package.sh
from Terminal to package your SAM package - Run
sh deploy.sh
from Terminal to deploy your SAM package to AWS - Once the script has completed (without errors), sign in into the AWS Console
- Navigate to the IAM service, edit the
ChangeStream-SendEmail-SendEmailRole-[random]
role - Add 2 inline policies
- For Amazon S3, add the
GetObject
policy on the*
ARN - For Amazon SES, add the
SendEmail
policy
- For Amazon S3, add the
- Test that the
SendEmail
lambda function works correctly (you can use theevent.json
file as a test event). - Navigate to the API Gateway console and select API Keys. Create an API Key and copy the value to the
awsApiGWKey
property of the trigger/config.js file. - Select the ChangeStream-SendEmail API and in the Actions menu, select Deploy API for the Stage deployment stage.
- In the ChangeStream-SendEmail/Stages menu, select the Stage stage and copy the Invoke URL value. Copy it to the
awsApiGWUrl
property of the trigger/config.js file.
You must configure a replica set for change streams to work. Follow the instructions below:
- Make sure the latest version of mtools is installed on your machine
- In the trigger folder, edit setup.sh and update the MONGO_LOCATION variable to point to your local MongoDB 3.6 installation root
- Run
sh setup.sh
to set up your MongoDB 3.6 replica set using mlaunch - Run
sh run.sh
to start your MongoDB 3.6 replica
- In the trigger folder, run
npm install
to install the required Node dependencies - Run
node trigger.js
to start listening to change streams coming from the devices collection of the demo database. - In a separate Terminal window, run
node addDoc.js
- this will add a document to thedevices
collection of thedemo
database. - Look at the window running
trigger.js
and if everything was properly configured you should get a Change Stream output log message, followed by a message confirming that the email was successfully sent. - Check your email inbox and you should find an email titled MongoDB 3.6 Change Stream notification for ecobee_1234.