Getting database credentials from AWS Secrets Manager in Spring Boot

AWS Secrets Manager Spring Boot

The last article was about how to get started with AWS Secrets Manager. We’ve created fixed database credentials and managed to access it using AWS CLI. In this article, we take it one step further. We are getting database credentials from AWS Secrets Manager in Spring Boot.

An example use case

Let’s say we have a Spring Boot application that we want to store its MySQL database in AWS Secrets Manager. That way when the application starts, it reads the credentials from the Secrets Manager and connects to the database that is hosted in a different data center (out of AWS).

To understand it better, let’s have a look at the below diagram,

AWS Secrets Manager Spring Boot
Architectural view

Creating the credentials

The first step is to create the AWS Secrets credentials, for that look at the previous post, here. Just keep in mind to select Credentials for other database.

Once the secret is created, keep the name somewhere, it’s needed later.

Application configuration

In this section, we go through how to configure the Spring Boot application. It’s rather simple and straightforward.

Adding aws-secretsmanager-jdbc dependency

To read the credentials, we use aws-secretsmanager-jdbc library by Amazon. It is super easy to configure.

Let’s add the following dependency to project,

Configuring application.properties

Now we have to configure application.properties so that the application can pick up the database credentials once it’s bootstrapped.

A usual database configuration looks like this,

But since we are relying on Secrets Manager JDBC we have to change it as follows,

As you can see, the JDBC URL prefix changed to jdbc-secretmanager.

Additionally, secret name is passed as the username property instead.

And lastly, the driver class name is set to what the library offers.

Running the application

Before running the application, we need to export three environment variables as follows,

Once it’s done we can run the application,

Well, as you have seen getting database credentials from AWS Secrets Manager in Spring Boot was very simple and straight forward.

The source code of this project is available on GitHub at the link below,
https://github.com/kasramp/springboot-aws-secrets-manager

Inline/featured images credits