How to Connect to Aurora PostgreSQL Database Using IAM Authentication and Node.js



I'm looking to connect the PostgreSQL Database using IAM authentication from Lambda written on Node.js

I see some java script code here but nothing specific for Node.js

I would like to authenticate connection to Aurora PostgreSQL using IAM Authentication.

Any pointer on this is really appreciated.

asked a year ago2183 views
2 Answers

You can use @aws-sdk/rds-signer to generate authentication token. After that, you can use auth token as password to connect to DB instance.

More info -

answered a year ago
  • Hi Vaihbav,

    I tried to implement the code but I'm getting below error when try to establish the connection from Lambda.

    error: pg_hba.conf rejects connection for host "x.x.x.x", user "iam_user", database "xx", SSL off\n at Parser.parseErrorMessage (/opt/nodejs/node_modules/pg-protocol/dist/parser.js:287:98)\n at Parser.handlePacket (/opt/nodejs/node_modules/pg-protocol/dist/parser.js:126:29)\n at Parser.parse (/opt/nodejs/node_modules/pg-protocol/dist/parser.js:39:38)\n at Socket.<anonymous> (/opt/nodejs/node_modules/pg-protocol/dist/index.js:11:42)\n at Socket.emit (events.js:314:20)\n at Socket.EventEmitter.emit (domain.js:483:12)\n at addChunk (_stream_readable.js:297:12)\n at readableAddChunk (_stream_readable.js:272:9)\n at Socket.Readable.push (_stream_readable.js:213:10)\n at TCP.onStreamRead (internal/stream_base_commons.js:188:23)


We able to successfully connect to the Aurora PostgreSQL from Lambda. We need to pass 'ssl:true' parameter while creating connection to Aurora PostgreSQL.

Steps to follow

  1. Enable IAM Authentication on DB Cluster.
  2. Create IAM Role/Permission with DB Connect Permission.
  3. PostgreSQL User with rds_iam Role.
  4. DB Cluster and Lambda on the Same VPC.

Node.JS code var aws = require('aws-sdk'); var pg = require('pg');

const dbRegion = 'eu-west-1'; const dbPort = 5432; const dbUsername = ‘iamuser’; const dbName = 'postgres'; const dbEndpoint = ' ';

let pgSigner = new aws.RDS.Signer({ region: dbRegion , hostname: dbEndpoint, port: dbPort, username: dbUsername }); logger.log('debug','PostgreSQL signer',pgSigner); let pgToken = pgSigner.getAuthToken(); logger.log('debug','PostgreSQL Login token',pgToken);

var client = new pg.Client({ host: dbEndpoint, port: dbPort, user: dbUsername, database: dbName , password: pgToken ssl: true }); client.connect(); var result=client.query('create table xyz(id int);') result.then((data) => { console.log('data - ' + JSON.stringify(data)); }).catch((error) => { console.log('error'+ error); });

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions