I am using AWS Secrets manager to protect the database credits of my REST API. I am using AWS Lambda, API Gateway and RDS (MySQL). Below is how I get them.
// Load the AWS SDK
var AWS = require('aws-sdk'),
region = "us-east-1",
secretName = "test-secret",
secret,
decodedBinarySecret;
// Create a Secrets Manager client
var client = new AWS.SecretsManager({
region: region
});
// In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
// See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
// We rethrow the exception by default.
exports.handler = (event, context, callback) => {
client.getSecretValue({
SecretId: secretName
}, function(err, data) {
if (err) {
throw err
} else {
// Decrypts secret using the associated KMS CMK.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if ('SecretString' in data) {
secret = data.SecretString;
} else {
let buff = new Buffer(data.SecretBinary, 'base64');
decodedBinarySecret = buff.toString('ascii');
}
}
// Your code goes here.
console.log(secret);
});
};
Below is the output
INFO {"username":"***","password":"***","engine":"mysql","host":"***.***.us-east-1.rds.amazonaws.com","port":3306,"dbname":"***","dbInstanceIdentifier":"***"}
I tried to extract the password like below
let pass = secret.password;
console.log(pass);
It gave the following
INFO undefined
How can I extract fields such as password
, username
, databasename
etc?
At first, you get back secret
as data.SecretString
, then now secret
just is a normal string. In your case, it is a JSON string, you must cast your string to a JSON object, then you can access the information by attribute name easily.
To do that, you can use JSON.parse method to convert a json string to json object:
var secret = `{"username":"***","password":"***","engine":"mysql","host":"***.***.us-east-1.rds.amazonaws.com","port":3306,"dbname":"***","dbInstanceIdentifier":"***"}
`;
const secretObj = JSON.parse(secret);
console.log(secretObj.host)