Connect to Amazon RDS PostgresQL Proxy with IAM Credentials using TypeORM

5.7k Views Asked by At

I'm trying to figure out how to connect to a RDS PG Proxy within a lambda function using TypeORM (so there's no issues establishing connections). I'm able to connect to the RDS instance with the Lambda function successfully - however, when I point the information at the proxy (change the environment variables within the Lambda function) I am greeted with the following error:

{
    "errorType": "Error",
    "errorMessage": "read ECONNRESET",
    "code": "ECONNRESET",
    "errno": "ECONNRESET",
    "syscall": "read",
    "stack": [
        "Error: read ECONNRESET",
        "    at TCP.onStreamRead (internal/stream_base_commons.js:205:27)"
    ]
}

Here is the code used to create the connection with TypeORM:

const config = getDBConfig();
connection = await createConnection(config);

// Retrieve database connection options
const getDBConfig = (): ConnectionOptions => {
  // Use IAM-based authentication to connect
  const signer = new RDS.Signer({
    region: "us-east-1",
    username: process.env.USERNAME,
    hostname: process.env.HOSTNAME,
    port: 5432,
  });

  // Retrieve password dynamically from RDS
  const token = signer.getAuthToken({
    username: process.env.USERNAME,
  });

  // Return configuration object
  return {
    username: process.env.USERNAME,
    host: process.env.HOSTNAME,
    port: 5432,
    password: token,
    ssl: {
      ca: fs.readFileSync("./config/rds-ca-2019-root.pem").toString(),
    },
    type: "postgres",
    database: "postgres",
    synchronize: false,
    entities: [],
  };
};

In terms of the two environment variables, HOSTNAME is equal to the URL provided by RDS proxy, and USERNAME is the username assigned within the secret for the RDS Proxy. Both the Lambda function and RDS Proxy have been given admin access, just to ensure there's no interference there (I know this is horrible, will reduce privileges once I get this working!). IAM authentication has been set to required for the proxy.

Update 8/14/2020

This article explains how you would connect RDS MySQL Proxy with TypeORM, still have not figured out how to connect to a RDS PG Proxy though.

https://dev.to/vikasgarghb/rds-proxy-via-sam-15gn

1

There are 1 best solutions below

0
On

I've finally found the instructions to setup DB user for PG in the AWS docs. Posting this here for anyone also having trouble finding them.

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.DBAccounts.html#UsingWithRDS.IAMDBAuth.DBAccounts.PostgreSQL

Basically you just need to add user to existing rds_iam group.

CREATE USER lambda;
GRANT ALL PRIVILEGES ON DATABASE postgres TO lambda;
GRANT rds_iam TO lambda;