【问题标题】:Access AWS Secrets Manager secret from AWS Lambda with JS使用 JS 从 AWS Lambda 访问 AWS Secrets Manager 密钥
【发布时间】:2020-10-26 08:49:38
【问题描述】:

我在 AWS Secrets Manager 中创建了一个密钥。尝试我从 AWS Secret manager 页面获得的示例代码不会产生任何结果。 下面是复制到 javascript AWS Lambda 函数中的示例代码dumbly

为了使其正常工作,我必须在开头添加 await 并在 API 调用中添加 .promise()

instruction on AWS Promises 之后,我只需要添加awaitpromise() 而不是使用回调函数:

AWS.Request.promise 方法提供了一种调用服务操作和管理异步流的方法,而不是使用回调

问题: 示例代码已经包含回调,为什么我需要添加awaitprommise?我错过了什么?


示例 AWS Lambda 函数代码:

exports.handler = async function(event, context, callback) {
    // Use this code snippet in your app.
    // If you need more information about configurations or implementing the sample code, visit the AWS docs:
    // https://aws.amazon.com/developers/getting-started/nodejs/

    // Load the AWS SDK
    var AWS = require('aws-sdk'),
        region = "eu-west-1",
        secretName = "MY_SUPER_SECRET",
        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.

    // ---> THIS await IS NEEDED TO MAKE IT WORK TOGETHER WITH THE promise() AT THE END
    await client.getSecretValue({SecretId: "MY_SUPER_SECRET"}, 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) {
                secret = data.SecretString;
                console.warn("secret")
                console.warn(secret)
            } else {
                let buff = new Buffer(data.SecretBinary, 'base64');
                decodedBinarySecret = buff.toString('ascii');
                console.warn("decodedBinarySecret")
                console.warn(decodedBinarySecret)
            }
        }
    
    // Your code goes here. 

    // ---> THIS promise IS NEEDED TO MAKE IT WORK TOGETHER WITH THE await AT THE BEGINING
    }).promise();
)    

【问题讨论】:

    标签: javascript amazon-web-services promise aws-lambda aws-secrets-manager


    【解决方案1】:

    如果您在 aws-call 上使用 .promise(),则不应向其传递回调(有关详细信息,请参阅 this)。而是在此承诺实现后处理响应(或错误)。

    我会改写为:

    function getAwsSecretPromise() {
        return client.getSecretValue({
            SecretId: "MY_SUPER_SECRET"
        }).promise();
    }
    
    const rethrowErrorCodes = ['DecryptionFailureException', 'InternalServiceErrorException', 'InvalidParameterException', 'InvalidRequestException', 'ResourceNotFoundException']
    
    exports.handler = async function (event, context, callback) {
    
        try {
            const data = await getAwsSecretPromise();
            if ('SecretString' in data) {
                secret = data.SecretString;
                console.warn("secret")
                console.warn(secret)
            } else {
                let buff = new Buffer(data.SecretBinary, 'base64');
                decodedBinarySecret = buff.toString('ascii');
                console.warn("decodedBinarySecret")
                console.warn(decodedBinarySecret)
            }
    
          // todo: do something with secret?
        } catch (err) {
            if (rethrowErrorCodes.some(errorCode => err.code === errorCode) {
                throw err;
            }            
            // todo: handle other errors?    
        }
    

    【讨论】:

    • 感谢您的回答@eol,但我实际上想知道为什么我必须让用户等待并承诺使其工作。我期待 AWS 提供的示例开箱即用。
    • .promise() 告诉 aws-client 将调用视为承诺而不是回调。使用await 只允许您等待这个承诺。除了await,您还可以使用then-handler:getAwsSecretPromise.then(result) => { ... /handle result })async/await 只允许更简洁的代码。
    猜你喜欢
    • 2020-09-28
    • 2021-06-25
    • 2023-01-01
    • 2020-07-23
    • 2021-04-11
    • 2019-02-15
    • 2019-12-01
    • 2020-09-29
    • 2021-10-29
    相关资源
    最近更新 更多