Publishing internal data to the cloud - Part 2
In part 1 we covered how to upload a file containing order data to an S3 bucket, and how to make the bucket emit a notification after receiving the file. In part 2 we’ll finish by using that notification to trigger a Lambda function that will import the data into a RDS database.
4. Import order data into a database when a new file is uploaded
Make a new Lambda function
In the Lambda service in the AWS console choose Create function:
- Author from scratch
- Function name - choose
order-import-function
- Runtime - Node.js 10.x
- Permissions > Execution role - choose Create new role from AWS policy templates, give the role a name, and then choose at least the Amazon S3 object read-only permissions template (my real function had additional permissions related to VPC access but I’m omitting the setup that for brevity)
Trigger on SNS
Once the function is created, then on the function configuration screen you can choose SNS as a trigger from the list on the left. On the Configure triggers card enter the ARN of the SNS topic created in part 1.
Write Lambda
Here’s the Node.js Lambda function that reads in the order JSON from S3 and inserts it into a SQL Server database:
Dependencies:
aws-sdk
- AWS SDK for JavaScriptmssql
- SQL Server client for Node./parser
is a utility module that parses the orders JSON and makes sure that it’s an array.
On the Environment variables card create these variables with these keys, filling in the values as appropriate for your database:
databaseName
rdsEndpoint
sqlPass
sqlUser
exports.handler
is the function that runs when the Lambda is triggered. This gets the name of the newly uploaded S3 file, gets the JSON contents of that file, parses the JSON back into an array of order objects, then sends the orders to the insertOrders
function.
insertOrders
uses mssql
to begin a transaction, drop the orders table if it already exists in the database, then add a new orders table that has a row for each order. If any errors are encountered it tries to rollback the transaction.