【发布时间】:2020-06-11 10:37:51
【问题描述】:
我们有一个 nodejs 应用程序,其中我们的基本要求是不使用 config.json 文件中的硬编码数据库密码,而是从 Google Cloud Secret Manager 中读取它,我能够从那里获取那个秘密值。
但是当我尝试通过 async function 在我的 models/index.js 中使用它时,我得到了 Promise { pending } 错误.
这是我的 secret_manager.js 文件:
let _ = require('lodash');
// Imports the Secret Manager library
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
let getSecret = async function (secretName) {
try {
if (!secretName) {
throw new TypeError('secretName argument is required to getSecret()');
}
if (typeof secretName !== 'string') {
throw new TypeError('secretName must be a string to getSecret()');
}
// Instantiates a client
console.info('Creating a SecretManagerServiceClient')
const client = new SecretManagerServiceClient();
console.info('Calling a accessSecretVersion')
const [version] = await client.accessSecretVersion({
name: secretName,
});
// Extract the payload as a string.
const payload = version.payload.data.toString('utf8');
if (_.isNil(payload) || _.isEmpty(payload)) {
let error = new Error()
error.name = 'SecretAccessError';
error.message = 'Invalid Secret Value for ' + secretName;
console.error(error);
throw error;
}
console.log("++payload=>")
console.log(payload)
return { Payload: payload }
} catch (error) {
error.name = "SecretAccessError"
console.error(error)
throw error;
}
}
module.exports = {
getSecret: getSecret
}
下面是我在 index.js 文件中的代码:
const secret = require('../secret_manager');
// The name of the secret
const secretName = 'my secret location in GoogleCloud'
let secretPassword;
let getSecret = async function(secretName)
{
let result = await secret.getSecret(secretName);
return result.Payload;
}
if(env=='development'){
secretPassword = getSecret(secretName);
}else{
secretPassword = getSecret(secretName);
}
console.log("secret passwprd is:")
console.log(secretPassword)
当我启动服务器时,这是我的输出:
[nodemon] starting `node start.js`
Creating a SecretManagerServiceClient
Calling a accessSecretVersion
secret passwprd is:
Promise { <pending> }
Running a GraphQL API server at http://localhost:4000/graphql in development environment!
++payload=>
**MYSECRETPASSWORD**
如何在 index.js 中使用我的秘密管理器值来进行数据库连接
【问题讨论】:
-
@sethvargo 感谢您的评论,我已经解决了我的问题并在下面发布了答案
标签: node.js dbconnection google-secret-manager