- Newest
- Most votes
- Most comments
Hi,
There are two ways in which AWS Lambdas can be created, via the online Lambda code editor [1] or by importing a deployment package in zip format with the code which you would like the lambda to be created from.
Since it will require the PostgreSQL connector in order to establish a connection to the RDS PostgreSQL Database, the code will have to be created locally then imported into the lambda console.
In order to achieve this, on your local machine you will need to create a nodejs project using Node.js via the terminal or command prompt. This can be done with the following commands:
mkdir lambdapostgres
cd lambdapostgres
npm init (accept all the defaults by pressing enter)
npm install —save pg
This creates a nodejs project names lambdapostgres with the postgres connecter added into the project as a dependency.
Once that is done, open the folder in a text editor of your choice then create a JavaScript file which will contain the code to connect to the RDS instance.
Copy the following code into the JavaScript file you just created:
//this imports the postgres connector into the file so it can be used
const { Client } = require('pg');
//instantiates a client to connect to the database, connection settings are passed in
const client = new Client({
user: '<your db username>',
host: '<your endpoint>',
database: '<your database name>',
password: '<your database password>',
port: 5432
});
//the lambda funtion code
exports.handler = async (event, context, callback) => {
try {
await client.connect();
callback(null, "Connected Successfully");
//your code here
} catch (err) {
callback(null, "Failed to Connect Successfully");
throw err;
//error message
}
client.end();
};
Modify it to include your instances connection details then, you will then need to zip up the project and go to the lambda console, create a new function, choose the target language in this case its Nodejs.
Once created you should be presented with the online code editor, under "Code entry Type" there is a drop down list, from there select upload a zip file last thing to do before saving is to rename the "Handler" to the javascript
file created earlier then click save.
Hope this helps!
/MrK
References:
[1] https://docs.aws.amazon.com/lambda/latest/dg/code-editor.html
[2] https://docs.aws.amazon.com/lambda/latest/dg/nodejs-create-deployment-pkg.html
Thanks so much! This is exactly what I needed to get going. I really appreciate the help! I was just getting to like the inline Lambda code editor. Oh well.
Sorry for the late response but have you looked at RDS Data API for Aurora Serverless? Makes it really simply to connect from Lambda -> Aurora Serverless
Relevant content
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated a year ago