Working with AWS Secret Manager
By: Zeeshan Baig
Tags: Amazon Web Services, AWS, Cloud Security, Security, Cloud

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

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. Administrator (DBA or Service or AWS) creates a record in AWS Secret Manager as a secret for an app for example MyWebAppDBCredentials 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. 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

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

Enter secret name and description, optionally enter Tags

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

Review your selections and click Store Secret

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: // https://aws.amazon.com/developers/getting-started/nodejs/ // Load the AWS SDK var AWS = require(‘aws-sdk’), region = “us-east-1”, //replace with your region secretName = “dev/mysql/mywebappdb”, // replace with your secret ID secret, decodedBinarySecret; // Create a Secrets Manager client var client = new AWS.SecretsManager({ region: region }); // In this sample we only handle the specific exceptions for the ‘GetSecretValue’ API. // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html // 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 object const secretJSON = JSON.parse(secret); // Read data from MYSQL database var mysql = require(‘mysql’); //Pass credentials info to connection var con = mysql.createConnection({ host: secretJSON.host, user: secretJSON.username, password: secretJSON.password, database: secretJSON.dbname }); //Query MySQL table con.connect(function (err) { if (err) throw err; con.query(“SELECT * FROM myproducts”, function (err, result, fields) { // change to your table name if (err) throw err; console.log(result); //display data from table process.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’ }

]

Conclusion

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.

@IamZeeshanBaig

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 www.datanextsolutions.com for more info.