You can use spring-cloud-starter-config
starter pom dependency to do it in a cleaner and trusted way & avoid Reinventing the Wheel. I have used it a lot and can assure that it works like charm.
Dependency is:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-vault-config</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
Usage: You must declare all the properties in application.properties
file (Assume these are default values) that you want values mapped from vault
.
Then you must declare a spring Configuration
annotated with @VaultPropertySource
as below:
@Configuration
@Profile("prod")
@VaultPropertySource(
value = {
"secret/${spring.application.name}/spring.mail.username",
"secret/${spring.application.name}/spring.mail.password",
})
public class VaultConfig {
@Bean
@ConditionalOnProperty("spring.cloud.vault.enabled")
public VaultTemplate vaultTemplate(
@Value("${spring.cloud.vault.host:localhost}") final String host,
@Value("${spring.cloud.vault.port:8200}") final String port,
@Value("${spring.cloud.vault.scheme:https}") final String scheme,
SessionManager sessionManager) {
VaultEndpoint vaultEndpoint = VaultEndpoint.create(host, Integer.valueOf(port));
vaultEndpoint.setScheme(scheme);
return new VaultTemplateExtension(
vaultEndpoint, new HttpComponentsClientHttpRequestFactory(), sessionManager);
}
}
Note:
I have used @Profile
annotation just to show how you can configure it for a profile only.
vaultTemplate
method receives it's valut
server config values either from specified properties or the default values separated by colon.
You can use @ConditionalOnProperty
decides when to enable properties to vault
secret mapping.
That's all. Now your props have values from vault. You can see how cleanly it populates the values to the properties.
Only one thing to ensure is that you need to specify the properties that receive value from vault in @VaultPropertySource
's value
property.