aws secrets manager spring boot example

AWS secret manager lets us to store the username and password securely and more importantly, this will save from not hard coding the credentials in the application. All just with an API call to Secrets Manager to retrieve the secrets programmatically.


Another great thing is automatic password rotation which secures our application double fold. Enough about secrets manager. You can read more about secrets manager at AWS Blog about secrets manager.



Configuration in spring-boot


Let’s learn how to retrieve the username and password from the secrets manager in java. The approach taken here will retrieve the username and password and inserts into database username and password.


Here, we use a ApplicationListener to listen to ApplicationPreparedEvent.


Dependencies



Add spring.factories in the given path.


Java Code


This is the hard way. Remember, in password rotation scenarios, if you are creating a new DB connection this will not work as password might have already changed.


The existing connections with the old password won’t be affected as AWS Secrets manager stores the old one too.


In that case, you need to restart the application to retrieve new password and make a new connection.


The easy way


There is an easy way which does not require your application to be restarted and with minimal configuration.


AWS Secrets Manager JDBC Library


The AWS Secrets Manager JDBC Library enables Java developers to easily connect to SQL databases using secrets stored in AWS Secrets Manager.

All it requires is one dependency and three lines of configuration code in your application.properties


Dependency


Add the following dependency in pom.xml



The latest version is found here in maven repository.


Application properties


Add the following line in application.properties.


This library will do all the behind the scenes stuff for you reducing the complexity.


Remember


Use appropriate driver based on your database. This is for Mysql.


For example usage, refer this official usage example in Github.

You can use specific environment variables for the database hostname, port and database name depending on the environment.


Resources



Keep Experimenting 🔎 

Keep Learning 🚀


Post a Comment

Previous Post Next Post