簡體   English   中英

我如何在 nodejs lambda 中使用 aws 秘密管理器

[英]how do I use aws secret manager with nodejs lambda

我試圖包裝示例代碼片段以獲取函數中的秘密,然后調用它,但它似乎不起作用。 我懷疑我是異步調用它,我需要同步調用它? 我只想要一個可以調用的函數來獲取一個秘密值並將其放入一個 var 中。

這是功能:

//outside exports.handler = (event, context, callback) => {
function getSecret(secretName) {
  // Load the AWS SDK
  var AWS = require('aws-sdk'),
      region = process.env.AWS_REGION,
      secretName = secretName,
      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.

  client.getSecretValue({SecretId: secretName}, function(err, data) {
      if (err) {
          if (err.code === 'DecryptionFailureException')
              // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
              // Deal with the exception here, and/or rethrow at your discretion.
              throw err;
          else if (err.code === 'InternalServiceErrorException')
              // An error occurred on the server side.
              // Deal with the exception here, and/or rethrow at your discretion.
              throw err;
          else if (err.code === 'InvalidParameterException')
              // You provided an invalid value for a parameter.
              // Deal with the exception here, and/or rethrow at your discretion.
              throw err;
          else if (err.code === 'InvalidRequestException')
              // You provided a parameter value that is not valid for the current state of the resource.
              // Deal with the exception here, and/or rethrow at your discretion.
              throw err;
          else if (err.code === 'ResourceNotFoundException')
              // We can't find the resource that you asked for.
              // Deal with the exception here, and/or rethrow at your discretion.
              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) {
              return data.SecretString;
          } else {
              let buff = new Buffer(data.SecretBinary, 'base64');
              return buff.toString('ascii');
          }
    }
  });
}

然后我叫它

// inside exports.handler = (event, context, callback) => {
var secret = getSecret('mySecret')
console.log('mysecret: ' + secret )

秘密變量總是undefined

編輯:異步只適用於承諾,所以我必須使我的函數異步並返回一個承諾:

async function mySecrets(secretName) {
    // Load the AWS SDK
    var AWS = require('aws-sdk'),
        region = process.env.AWS_REGION,
        secretName = secretName,
        secret,
        decodedBinarySecret;

    // Create a Secrets Manager client
    var client = new AWS.SecretsManager({
        region: region
    });

    return new Promise((resolve,reject)=>{
        client.getSecretValue({SecretId: secretName}, function(err, data) {

            // 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.
            if (err) {
                reject(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) {
                    resolve(data.SecretString);
                } else {
                    let buff = new Buffer(data.SecretBinary, 'base64');
                    resolve(buff.toString('ascii'));
                }
            }
        });
    });
}

.....
// inside handler
exports.handler = async (event) => {
....
var value = await mySecrets('mysecret')

您需要等待異步調用完成。

在您的主處理程序中,您將擁有如下內容:

// inside your main handler
exports.handler =  async function(event, context) {
    var secret = await getSecret('mySecret')
    console.log('mysecret: ' + secret )

    return ...
    }

如果有人需要解決這個問題,這里有一個更簡單的例子:

const result = await client
  .getSecretValue({
    SecretId: AWSConfig.secretName,
  })
  .promise();

const parsedResult = JSON.parse(result.SecretString);

aws-sdk提供了兩種從 API 取回值的方法。 您可以使用本機回調機制,如上所示,或者您可以改為在調用鏈的末尾使用.promise()將 API 調用轉換為其等效的 promise。

例如

const data = await (secretManager.getSecret({ SecretId }).promise();

如果您正在使用await那么您的函數需要與調用它的所有函數一樣async ,除非他們選擇使用 Promise 的then / catch等。

我創建了一個同步解決方案,您可以在這里找到: https : //github.com/jwerre/secrets

使用此包,您可以將所有機密加載到特定命名空間中,如下所示:

const config = require('@jwerre/secrets').configSync({
    region: 'us-east-1',
    env: 'production',
    namespace: 'my-namespace',
});

這將檢索您所有可能不完全是您想要的秘密。 如果你想要一個秘密,你可以這樣做:

const config = require('@jwerre/secrets').secretSync({
    region: 'us-west-2'
    id: '/my-co/apis/'
});

更好的方法是在異步 lambda 函數中執行此操作

示例key:val => password:rootPassword

const secret = await secretClient.getSecretValue({SecretId: 'SecretKeyName'}).promise().then((data) => {
        return JSON.parse(data.SecretString);
})

然后以secret.password訪問它。

注意:環繞try/catch塊以自動處理錯誤。

有一種更簡單的方法可以從秘密管理器中讀取它。

let secretManager = new SecretsManager({ region: 'region-name' });
const data = await secretManager.getSecretValue({ SecretId: 'secretid' }).promise();
console.log(`data is: ${JSON.stringify(data)}`);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM