Working with AWS Secret Manager

Image for post
Image for post

In my previous post Exploring AWS Secret Manager, we learned about some key benefits of using AWS Secret Manager. In this post, we will explore how to use it with a practical example.

How it Works

You can use Secret Manager to store, rotate, monitor, and control access to secrets such as database credentials, API keys, and OAuth tokens.

I have discussed the benefits and workflow of Secret Manager in my other post check it out

AWS Secret Manager Workflow

The above slide describes the typical application workflow when working with AWS Secret Manager

  1. The DBA or Service admin creates a service account credential to use the service for a particular app. For example, DBA creates a username and password for MyWebApp to access the database.
  2. Administrator (DBA or Service or AWS) creates a record in AWS Secret Manager as a secret for an app for example MyWebAppDBCredentials
  3. When an application needs a credential it queries AWS Secret Manager through secure HTTPs and TLS channel, AWS then returns the credentials to the app. for example, the client calls Secret Manager to retrieve entries for MyWebAppDBCredentials.
  4. The app or client parse the credentials and use it in the application as required. For example, in a connection string or API call.

Example Overview

In this example, we will store a password of MYSQL RDS database, retrieve it in a Node.js function using AWS SDK

Creating a Secret

The first step is to create a secret open AWS Console and go to AWS Secret Manager

Click on Store a new secret button

Image for post
Image for post

Select Secret Type, in our case we are storing credentials for our MySQL RDS database. Enter the username and password and select the RDS database the credentials belong to

Image for post
Image for post

Enter secret name and description, optionally enter Tags

Image for post
Image for post

Configure rotation function, I have chosen default which is Disable automatic rotation. Enabling rotation is a topic for another post

Image for post
Image for post

Review your selections and click Store Secret

Image for post
Image for post

Now you have stored the secret, let’s see an example to work with it

Using a Secret

Following Node.js code is reading credentials from AWS Secret Manager then passing credentials info to the Connection string in Node.js function

// Use this code snippet in your app.// If you need more information about configurations or implementing the sample code, visit the AWS docs:// Load the AWS SDKvar AWS = require(‘aws-sdk’),region = “us-east-1”, //replace with your regionsecretName = “dev/mysql/mywebappdb”, // replace with your secret IDsecret,decodedBinarySecret;// Create a Secrets Manager clientvar client = new AWS.SecretsManager({region: region});// In this sample we only handle the specific exceptions for the ‘GetSecretValue’ API.// See We rethrow the exception by default.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 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’);}}//Parsing secret JSON objectconst secretJSON = JSON.parse(secret);// Read data from MYSQL databasevar mysql = require(‘mysql’);//Pass credentials info to connectionvar con = mysql.createConnection({host:,user: secretJSON.username,password: secretJSON.password,database: secretJSON.dbname});//Query MySQL tablecon.connect(function (err) {if (err) throw err;con.query(“SELECT * FROM myproducts”, function (err, result, fields) { // change to your table nameif (err) throw err;console.log(result); //display data from tableprocess.exit(); //exit node.js server});});});

Execute the above code by writing it in a file readsecret.js The output of the above code is as follows

$ node readsecret.js[
RowDataPacket { product_id: 100, product_desc: ‘PC’ },
RowDataPacket { product_id: 200, product_desc: ‘MAC’ },
RowDataPacket { product_id: 300, product_desc: ‘iPHONE’ },
RowDataPacket { product_id: 400, product_desc: ‘iPAD’ },
RowDataPacket { product_id: 500, product_desc: ‘PRINTER’ }


In this post, we stored the credentials of our MySQL RDS database in AWS Secret Manager and later retrieved the credentials from a secret manager and use it in our application securely.

I hope you like this post.


About DataNext

DataNext Solutions is a US-based system integrator, specialized in Cloud, Security, and DevOps technologies. As a registered AWS partner, our services comprise of any Cloud Migration, Cost optimization, Integration, Security and Managed Services. Click here and Book a Free assessment call with our experts today or visit our website for more info.

Written by

Cloud Security Expert & CEO of DataNext Solutions, helping people every day with the latest tech. Connect @LinkedIn

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store