AWS Lambda function to connect to Postgresql database
Does anyone know how I can connect to PostgreSQL database using AWS Lambda function. I searched the internet for it, but I couldn't find anything about it. If you could tell me how to do this, that would be great.
If you can find something wrong with my code (node.js) that would be great, otherwise can you tell me how to do it?
exports.handler = (event, context, callback) => {
"use strict"
const pg = require('pg');
const connectionStr =
"postgres://username:password@host:port/db_name";
var client = new pg.Client(connectionStr);
client.connect(function(err){
if(err) {
callback(err)
}
callback(null, 'Connection established');
});
context.callbackWaitsForEmptyEventLoop = false;
};
Code raises error: cannot find module 'pg'
I wrote it directly on AWS Lambda and didn't upload anything if that matters.
source to share
I wrote it directly on AWS Lambda and didn't upload anything if that matters.
Yes it does matter! Lambda does not provide third party libraries out of the box. Once you have a dependency on a third party library, you need to pin and load your Lambda code manually or using the API.
For more information: Lambda Execution Environment and Available Libraries
source to share
You need to specify Create Deployment Package (Node.js)
A simple scenario . If your custom code only needs the AWS SDK library, you can use the built-in editor in the AWS Lambda Console. Using the console, you can edit and upload your code to AWS Lambda. The console will close your code with the appropriate configuration information in a deployment package that the Lambda service can start.
and
Advanced script . If you are writing code that uses other resources, such as a graphics library for image processing, or you want to use the AWS CLI instead of the console, you need to create a Lambda function deployment package first, and then use the console or CLI to download the package.
Your case, like mine, falls under the extended scenario. Therefore, we need to create a deployment package and then download it. Here's what I did -
- mkdir deployment
- deploy cd
- vi index.js
- write your lambda code in this file. Make sure your handler name is index.handler when you create it.
- npm install pg
- You should see a node_modules directory created in the deployment directory that has multiple modules in it.
- Deployment directory package to zip file and upload to Lambda.
- You must be good then
NOTE. npm install will install node modules in the same directory under the node_modules directory if it doesn't see the node_module directory in the parent directory. To be the same first npm init
, then npm install
to make sure the modules are installed in the same directory for deployment.
source to share