Spring Boot | Get your secrets from AWS Secrets Manager
Getting the secrets from AWS Secrets Manager from your Spring Boot application is just a piece of cake.
Let’s explore AWS Secrets Manager and create few secrets in it and then read them from a Spring Boot application.
The full source code is available in this GitHub repository.
Start by having AWS CLI installed in your local (follow this guide). This is required to configure AWS access credentials in your local machine.
Next, let’s log in to the AWS console and go to AWS Secrets Manager.
We will create a secret to store database credentials (just for demo).
Add the following key/value pairs (you can use any text for key/value):
dbUser : johndoe
dbPassword : helloworld
Give your secret a name (dev/my-app/database-creds
):
You can choose to rotate your secret automatically after a certain duration. We will keep it disabled for now.
That’s almost it, you will be even offered sample code snippets in multiple languages in order to get your secrets, but who needs these when we have the mighty Spring Boot backing us 😄.
Finally, we will get a message which says that our secret has been successfully stored:
Let’s add one more secret using the same process. This time, with following details:
secret name : dev/my-app/oauth-credskey/value pairsclientId : dummy-client-id
clientSecret : dummy-client-secret
Let’s head over to our Spring Boot app now, I am not sharing steps to create a new Spring Boot app here.
We essentially need this dependency which will do all the magic for us : spring-cloud-starter-aws-secrets-manager-config
Here is the snippet from build.gradle
:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation('io.awspring.cloud:spring-cloud-starter-aws-secrets-manager-config:2.4.2')
}
We need to add all our secrets intoappliction.yml
under the spring.config.import
property:
Now let’s bring the secrets into our code. We can just use @Value
annotation to read the values of the keys defined in our secrets. Just make sure to use the exact same “key” names that we defined in our secrets in the AWS Secrets Manager.
Run the app and here is the output:
We have successfully read the secrets in our Spring Boot app.
One last thing, note that there is one secret that has been marked as optional
in application.yml
:
- optional:aws-secretsmanager:dev/my-app/some-other-creds
We didn’t create any secret named some-other-creds
and if we hadn’t used optional
here then our app would have failed to start up. So to avoid start up failure because of missing secret, you can mark your secret as optional
in the configuration.
Thanks for reading!