How to use AWS Secret manager with Node JS lambda

Code With Travel
4 min readFeb 17, 2021

What Is AWS Secrets Manager?

In the past, when you created a custom application to retrieve information from a database, you typically embedded the credentials, the secret, for accessing the database directly in the application. When the time came to rotate the credentials, you had to do more than just create new credentials. You had to invest time to update the application to use the new credentials. Then you distributed the updated application. If you had multiple applications with shared credentials and you missed updating one of them, the application failed. Because of this risk, many customers choose not to regularly rotate credentials, which effectively substitutes one risk for another.

Secrets Manager enables you to replace hardcoded credentials in your code, including passwords, with an API call to Secrets Manager to retrieve the secret programmatically. This helps ensure the secret can’t be compromised by someone examining your code, because the secret no longer exists in the code. Also, you can configure Secrets Manager to automatically rotate the secret for you according to a specified schedule. This enables you to replace long-term secrets with short-term ones, significantly reducing the risk of compromise.

Step 1: Create and store your secret in AWS Secrets Manager

  • Sign in to the AWS Secrets Manager console at https://console.aws.amazon.com/secretsmanager/.
  • On either the service introduction page or the Secrets list page, choose Store a new secret.
  • On the Store a new secret page, choose Other type of secret. You choose this type of secret because your secret doesn’t apply to a database.
  • Under Specify key/value pairs to be stored in the secret, in the first field, type UserName. To configure a password, add a value in the next field.
  • For Select the encryption key, choose DefaultEncryptionKey.
  • In the Tags section, add desired tags in the Key and Value — optional text fields.
  • Choose Next.
  • In this tutorial, choose Disable automatic rotation, and then choose Next.
  • On the Review page, you can check your secret settings and To save your changes, choose Store.

Now let’s try to user this Secret Manager in Lambda function using Node JS.

Lambda runs your code only when needed and scales automatically, from a few requests per day to thousands per second. You pay only for the compute time that you consume — there is no charge when your code is not running. With Lambda, you can run code for virtually any type of application or backend service, all with zero administration. Lambda runs your code on a high-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring and logging.

Create a Lambda function with default function code

  • Open the Functions page on the Lambda console.
  • Choose Create function.
  • Under Basic information, do the following:
  • Give Function name, enter Secreatmanager-function.
  • For Runtime, confirm that Node.js 14.x is selected.
  • Choose Create function.

To invoke a function

  • In the upper right corner, choose Test.

AWS Roles. Secrets Manager Policy

In order for your AWS resources to access Secrets Manager, the resources needs to have the correct permissions to do so.

This means that when you assign a role to your lambda, that role must have the SecretsManagerReadWrite policy attached to it to give it the required permission to access Secrets Manager.

Add following code to Lambda Function.

var aws = require("aws-sdk");
var client = new aws.SecretsManager({
region: 'ap-southeast-1' // Your region
});
var secret, decodedBinarySecret;
//context.callbackWaitsForEmptyEventLoop = false;
exports.handler = (event, context, callback) => {
client.getSecretValue({
SecretId: 'MyFirstSecret'
}, 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;
} else {
let buff = new Buffer(data.SecretBinary, 'base64');
decodedBinarySecret = buff.toString('ascii');
}
}
// Your code goes here.
console.log(secret);
});
};

Now Deploy the function and Run the function (choose Test).

You will get secret values.

--

--