2

我们有一个 nodejs 应用程序,其中我们的基本要求是不使用config.json文件中的硬编码数据库密码,而是从Google Cloud Secret Manager读取它,我可以从那里获取该秘密值。

但是当我尝试通过异步函数在我的模型/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 中使用我的秘密管理器值来续集数据库连接

4

1 回答 1

1

我为我的秘密密码添加了一个 then 块,例如:

    secretPassword.then(function (res) {
    -----Rest of the logic inside this---
    }

module.exports = db;

这对我有用

于 2020-03-13T10:09:15.660 回答