我正在尝试使用AWS Secrets Manager来获取我的RDS凭证,
Secrets Manager SDK能够正确获取Secret,
但是我无法将其导出回我的调用文件。
我有2个文件-
1。 index.js-
var mysql = require('mysql');
var secretsManager = require('./secrets-manager');
exports.handler = (event, context, callback) => {
secretsManager.getDbCredentialFromSecretsManager(function(err,creds) {
if (err) {
console.log(err);
callback(err, null);
}
else{
console.log("Creds ", creds);
var connection = mysql.createConnection(creds);
connection.connect(function(err) {
if (err) {
console.error(err.stack);
callback(err,null);
}
else{
callback(null,connection);
}
});
}
});
}
2。 secrets-manager.js-
var AWS = require('aws-sdk');
var constants = require('/opt/nodejs/utils/constants');
module.exports = {
getRDSCredsFromSM
};
function getRDSCredsFromSM (callback) {
var response = {};
let secretName = "secretId";
var client = new AWS.SecretsManager({
region: constants.aws.region
});
client.getSecretValue({SecretId: secretName}, function(err, data) {
if (err) {
console.log(err);
callback(err, null);
}
else {
if ('SecretString' in data) {
let secret = data.SecretString;
secret = JSON.parse(secret);
console.log("secret",secret);
callback(null, secret);
} else {
let buff = new Buffer(data.SecretBinary, 'base64');
let decodedBinarySecret = buff.toString('ascii');
callback(null, decodedBinarySecret);
}
}
});
}
我觉得在Node方面我犯了一些错误,
这就是为什么回调无法正常运行的原因,
Lambda超时,
而且日志在creds变量中什么也没显示-
console.log("Creds ", creds);
答案 0 :(得分:2)
工作代码-
let async = require('async');
let AWS = require('aws-sdk');
module.exports = {
getDbCredentialFromSecretsManager
};
const TAG = '[SECRETS-MANAGER-UTIL->';
function getDbCredentialFromSecretsManager (constants, callback) {
let response = {};
const METHOD_TAG = TAG + 'getDbCredentialFromSecretsManager->';
async.waterfall([
function(callback) {
let client = new AWS.SecretsManager({
region: constants.aws.region
});
client.getSecretValue({SecretId: constants.aws.sm}, function(err, data) {
if (err) {
console.log(METHOD_TAG,err);
callback(err, null);
}
else {
console.log(METHOD_TAG, 'Secrets Manager call successful');
if ('SecretString' in data) {
let secret = data.SecretString;
secret = JSON.parse(secret);
response.user = secret.username;
response.password = secret.password;
response.host = secret.host;
response.database = constants.db.database;
callback(null, response);
} else {
let buff = new Buffer(data.SecretBinary, 'base64');
let decodedBinarySecret = buff.toString('ascii');
callback(null, decodedBinarySecret);
}
}
});
}
],
function(err, response) {
if (err) {
console.log(METHOD_TAG, err);
callback(err, response);
}
else {
callback(null, response);
}
});
}