I'm trying to decrypt some environment variables, using AWS Key Management Service (KMS), from an AWS Lambda function, and then posting a tweet using the decrypted credentials. However, the environment variables are not being decrypted before I utilize the Twitter object. This is causing authentication to fail.
How can I make sure that the Twitter object, in the code below, is fully instantiated / initialized, before calling its member functions? Should I be using promises instead?
var AWS = require('aws-sdk');
var Twitter = require('twitter');
var s3 = new AWS.S3();
var kms = new AWS.KMS();
function DecryptEnvironmentVariable(creds, varname) {
console.log(`Decrypting environment variable named ${varname}`);
console.log(process.env[varname]);
params = {
CiphertextBlob: process.env[varname]
}
kms.decrypt(params, function (err, data) {
if (err) {
console.log(err);
}
else {
console.log("Successfully decrypted envrionment variable.");
return data.Plaintext;
}
});
}
exports.tweet = function (event, context) {
// Instantiate the Twitter object
var twitterclient = new Twitter({
consumer_key: DecryptEnvironmentVariable('TWITTER_CONSUMER_KEY'),
consumer_secret: DecryptEnvironmentVariable('TWITTER_CONSUMER_SECRET'),
access_token_key: DecryptEnvironmentVariable('TWITTER_ACCESS_TOKEN_KEY'),
access_token_secret: DecryptEnvironmentVariable('TWITTER_ACCESS_TOKEN_SECRET'),
})
// Post a new tweet
twitterclient.post('statuses/update', { status: "messagegoeshere" })
.then(function(tweet) {
console.log("Tweet was successfully posted!");
})
.catch(function(error) {
console.log("Error occurred while posting tweet. :(");
console.log(error);
});
}