Using a Jenkins variable in application properties file of spring boot app
For reading via application.properties:
Set the value of VAR to the java system or environment and read it in application.properties
like
my.app.prop=${ENV_VARIABLE}
For reading in Jenkins file:
In order to read it in jenkins file, write a groovy script and read the property like System.properties[ENV_VARIABLE]
Note: I assuming your Spring boot app and Jenkins runs on the same JVM.
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'svalut
server config values either from specified properties or the default values separated by colon.You can use
@ConditionalOnProperty
decides when to enable properties tovault
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.
An alternative approach is to use a JAVA Class to read the jenkins var and write to a properties file. Then read it from the properties file.Suppose for example, If USERNAME is one of the String parameters that you use to build the jenkins job, then the same can be accessed in a JAVA Class by using the below code.
System.getProperty("USERNAME");
You can read it directly into the properties file as mentioned by GAK as well.e.g.
${env.JOB_NAME}