简体   繁体   中英

Get secrets in AWS lambda node.js

Can anyone provide a simple, complete node.js lambda function where I can get a secret from secrets manager and use it? I am struggling with the async/await process. I have already tried several suggestions from other posts, but all of them, at the end, can't really use the secret in the main function. For example, I have a main function and call a second function to retrieve the secret:

xxx = retrieve_secret('mysecret');

Then, in the retrieve_secret function I am able to retrieve the secret, I can print it using console.log, but when I try to use it in the main function, it says "Promise ".

Please, help. Thanks in advance!

So, after a few days working on it, I was finally able to solve it:) Here is the code that worked for me:

exports.handler = async (event, context, callback) => {

   // Get Secret
   var AWS       = require('aws-sdk');
   var MyPromise = new AWS.SecretsManager();

   var Vsecret   = await MyPromise.getSecretValue({
      SecretId: 'enter-the-secret-id-here'
      }).promise();

   var MyOpenSecret = JSON.parse(Vsecret.SecretString);

   // From here, we can use the secret:
   var Vhost     = MyOpenSecret.host;
   var Vuser     = MyOpenSecret.username;
   var Vpassword = MyOpenSecret.password; 
   var Vdatabase = .....

Looking at your question seems you are not able to read response from retrieve_secret('mysecret') method as you have mentioned it return promise, you can read it by using.then() after promise. Try doing this -

xxx.then(res => {
    console.log(res)
})

Or here is the code to call get your secret details:

import AWS from "aws-sdk";

getSecretValue(secretName: string): Promise<string> {
        const client = new AWS.SecretsManager({ 
            region: '',
            accessKeyId: '',
            secretAccessKey: '',
        });
        const secretId = "secretName";
        return new Promise((resolve, reject) =>
            client.getSecretValue({ SecretId: secretId }, (err, data) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(data.SecretString);
                }
            })
        );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM