1

我需要使用从秘密管理器中检索到的秘密来配置 knexfile.js。我从秘密管理器中检索秘密并将其存储在秘密变量中并在配置中使用它。

var AWS = require('aws-sdk'),
endpoint = "abcd",
region = "us-east-1",
secretName = "abcd",
secret,
binarySecretData;

var client = new AWS.SecretsManager({
endpoint: endpoint,
region: region
});
client.getSecretValue({
SecretId: secretName
}, function (err, data) {
if (err) {
if (err.code === 'ResourceNotFoundException')
    console.log("The requested secret " + secretName + " was not found");
else if (err.code === 'InvalidRequestException')
    console.log("The request was invalid due to: " + err.message);
else if (err.code === 'InvalidParameterException')
    console.log("The request had invalid params: " + err.message);
} else {
if (data.SecretString !== "") {
    secret = data.SecretString;
} else {
    binarySecretData = data.SecretBinary;
}
}
});
module.exports = {
development: {
    client: secret.localClient,
    connection: {
        host: secret.localHost,
        user: secret.localUser,
        password: secret.localPassword,
        database: secret.localDatabase,
        charset: "utf8"
    }
},
};

但它显示错误 TypeError: Cannot read property 'localClient' of undefined

4

2 回答 2

1

获取秘密是异步操作,因此secret当您尝试从 knexfile.js 导出它时,您的变量还不存在。

您可能应该在启动虚拟机时首先获取要存储在本地某处的秘密,然后在 knexfile.js 中同步读取它,例如从本地文件中读取。

于 2018-07-01T18:24:30.690 回答
1

现在这在 Knex 中是可能的。您可以将异步函数传递给configuration.

async function getConfig() {
  return new Promise((resolve, reject) => {
   client.getSecretValue({ SecretId: 'SECRETID' }, function(
    err,
    data
  ) {
    if (err) {
      console.log('secretsErr', err);
      reject(err);
    } else {
      console.log('Secrets Manager call successful');
      if ('SecretString' in data) {
        let secret = data.SecretString;
        secret = JSON.parse(secret);
        const config = {
          user: secret.DbUser,
          password: secret.DbPassword,
          server: secret.DbServer,
          database: secret.DbDatabase,
          expirationChecker: () => false,
          options: {
            encrypt: true,
            enableArithAbort: true
          }
        };
        resolve(config);
      } else {
        console.log('no secret found');
        reject();
      }
    }
  });
}

let knex = require('knex')({
  client: 'mssql',
  connection: async function() {
    return await getConfig();
  }
});
于 2020-11-24T04:30:41.843 回答