opt*_*con 7 amazon-web-services node.js
我需要在AWS Lambda函数中解密许多加密的环境变量.他们给出了一些示例代码,但我不想为我需要解密的每个值运行一个巨大的块:
const AWS = require('aws-sdk');
const encrypted = process.env['my_password'];
let decrypted;
function processEvent(event, context, callback) {
// TODO handle the event here
}
exports.handler = (event, context, callback) => {
if (decrypted) {
processEvent(event, context, callback);
} else {
// Decrypt code should run once and variables stored outside of the function
// handler so that these are decrypted once per container
const kms = new AWS.KMS();
kms.decrypt({ CiphertextBlob: new Buffer(encrypted, 'base64') }, (err, data) => {
if (err) {
console.log('Decrypt error:', err);
return callback(err);
}
decrypted = data.Plaintext.toString('ascii');
processEvent(event, context, callback);
});
}
};
Run Code Online (Sandbox Code Playgroud)
我想知道AWS SDK是否包含一个允许我一次解密多个值的函数.如果不这样做,有没有办法优雅地将这些调用链接在一起,这样他们就不会占用我这个简单功能的~75行?
小智 13
您可以使用promises来实现此目的.请参阅下面的示例,以通过KMS解密用户名和密码.您可以根据需要向decryptPromises
阵列添加任意数量的其他解密承诺:
const AWS = require('aws-sdk'); const encrypted = { username: process.env.username, password: process.env.password }; let decrypted = {}; function processEvent(event, context, callback) { //do work } exports.handler = (event, context, callback) => { if ( decrypted.username && decrypted.password ) { processEvent(event, context, callback); } else { const kms = new AWS.KMS(); const decryptPromises = [ kms.decrypt( { CiphertextBlob: new Buffer(encrypted.username, 'base64') } ).promise(), kms.decrypt( { CiphertextBlob: new Buffer(encrypted.password, 'base64') } ).promise() ]; Promise.all( decryptPromises ).then( data => { decrypted.username = data[0].Plaintext.toString('ascii'); decrypted.password = data[1].Plaintext.toString('ascii'); processEvent(event, context, callback); }).catch( err => { console.log('Decrypt error:', err); return callback(err); }); } };
您可以在SDK文档的Support for Promises中找到有关如何为AWS SDK实现promises的更多信息.
归档时间: |
|
查看次数: |
1712 次 |
最近记录: |