Currently using Nodejs, I connect to RDS MySQL database using below approach,
const mysql = require("mysql");
const environment = require("../core/environment/environment");
const connection = mysql.createPool({
host: environment.mysql.host,
port: environment.mysql.port,
user: environment.mysql.user,
password: environment.mysql.password, // is there a way to avoid it
connectionLimit: 10
});
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
connection.end();
The problem with above approach is I have to expose/reveal/store password in the environment file which I don't want.
I recently came across this article https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.html which allows to access DB using IAM authentication without using password but it doesn't describe any way to deal with Nodejs platform. However, it has other platform articles eg Python,.NET etc but not Nodejs.
I googled other ways out but can't seem to find any reference how to access RDS in Nodejs app without password.
How can I achieve it ?
You can use rds-signer
package (part of aws-sdk
). This should help you to obtain temporary tokens using your IAM Default config or IAM role for secure connections to your RDS instance.
const signer = new Signer({
/**
* Required. The hostname of the database to connect to.
*/
hostname: "db.us-east-1.rds.amazonaws.com",
/**
* Required. The port number the database is listening on.
*/
port: 8000,
/**
* Required. The username to login as.
*/
username: "user1",
/**
* Optional. The AWS credentials to sign requests with. Uses the default credential provider chain in not specified.
*/
credentials: fromNodeCredentialProvider(),
/**
* Optional. The region the database is located in. Uses the region inferred from the runtime if omitted.
*/
region: "us-east-1",
/**
* Optional. The SHA256 hasher constructor to sign the request.
*/
sha256: HashCtor,
});
const token = await signer.getAuthToken();
Reference: https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-rds-signer/