In the last blog i have explained how to integrate different environment variable files in the NodeJS application. In this blog i am going to show you how to add AWS secret manager in your NodeJS application to fetch secrets from AWS directly.

Table of Content

  1. Install AWS Cli
  2. Configure AWS secrets
  3. How to create secrets in AWS secret manager?
  4. Add Secret manager code snippet to your application
  5. Call Secret manager code snippet

1. How to install AWS Cli?

To get started you have to install AWS cli on your system. Follow this link to install AWS cli on windows system(You can find links for other OS as well). Now download MSI file. Now run downloaded MSI installer. Once installation completes you can confirm the installation by typing following command

C:\Users>aws --version
aws-cli/2.7.31 Python/3.9.11 Windows/10 exe/AMD64 prompt/off

2. How to Configure AWS Secrets on your machine?

I am assuming you already have AWS access key ID and Secret with you. If you don't have these then you can follow this link to download your AWS credentials. Now to configure AWS credentials type following command

C:\Users>aws configure
AWS Access Key ID [****************34Xe]:<type your Access Key ID>
AWS Secret Access Key [****************sdE4]:<type your Secret Access Key>
Default region name [ap-south-1]: <enter default region>
Default output format [None]:

Once you are done with the above step then you can confirm the same by typing following command

C:\Users>aws configure list

This command will give you list of configuration you have setup on your machine.

3. How to create secrets in AWS secret manager?

Now to get secrets in your NodeJS application, you have to add it in the AWS secret manager. To add secrets go to AWS then type AWS secret manager in the search box and click on AWS secret manager in search result. It will open AWS secret manager page.

Now you can click store a new secret and choose secret type as other type of secret and add secrets as key-value pairs

4. Add Secret manager code snippet to your application

Once you are done with the all steps mentioned above then add following code in your NodeJS application. You can add it inside config/env.config.js file(you can place below code block anywhere in you application but i like more organized and better names :))

var AWS = require('aws-sdk'),
region = "ap-south-1",
secret,
secretName="your-aws-secret-name", // You can load this secret based on the environment
decodedBinarySecret;
// Create a Secrets Manager client
var client = new AWS.SecretsManager({
region: region
});
client.getSecretValue({SecretId: secretName}, 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 key.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if ('SecretString' in data) {
secret = JSON.parse(data.SecretString);

// Add all secret which is present on AWS to process.env
// which will be available in all over application
for(const envKey of Object.keys(secret)) {
process.env[envKey] = secret[envKey];
}
} else {
let buff = new Buffer(data.SecretBinary, 'base64');
decodedBinarySecret = buff.toString('ascii');
}
}

// console log in case of error
console.log(err);
});

In this code snippet, i am using aws-cli node package which is basically used to perform any AWS operations from NodeJS application. Now I am defining secret name and region. Below that i am creating an instance of AWS secret manager. In the next line i am calling getSecretValue function which takes SecretId as argument which will be your secret name which you have created in the AWS Secret manager. getSecretValue is an asynchronous function, in the callback function there are two arguments err and data. I am handling err based on error types. If i dont get any error the in the else i am checking if data has SecretString if yes then parse SecretString from data and add all key value pair to process.env. This line will make sure whatever is present in your secret manager which will be available in your all over application.

5. Call Secret manager code snippet

Now the last question arise, where to call this secret manager code snippet? You have to call this snippet before calling any packages or files. So better place is your NodeJS startup file which will be your index.js or server.js or app.js whatever you have named it. For me its index.js so you can call it as follows

require("./config/env.config");
const express = require("express");
/**
* Remaining codes ...
*/

Conclusion

Sometime its not secure to add credentials in the .env file of your NodeJS application. So its better to add it in the AWS Secret Manager so that no one will get the credentials if they don't have your AWS credentials. Thanks for reading. Happy Coding.