How can Java code read a Jenkins Global credentials during Jenkins build?

Viewed 2270

I have a Java project that builds on Jenkins. This code needs a Secret file (.pem format) to run. I can't save the file in the Java project itself (security reasons).

The file format is key_v2-XXXXX.pem and contents are

-----BEGIN PRIVATE KEY-----
XXX
XXXX
-----END PRIVATE KEY-----

Currently, the Java code is accessing the Secret file present in the Local. So the local build is fine. But when this code is executed on Jenkins, the build fails because it can't find the local file or the file is not accessible to Jenkins.

I've added the Secret File as a Global Credential (unrestricted) in Jenkins. (Reference - https://jenkins.io/doc/book/using/using-credentials/)

I need to find a way for the Java code to access this Secret file(stored in Jenkins) while running the Jenkins build.

Or Is there any other way to handle this situation?

1 Answers

There are many ways to do this.

The easiest of which is using the Jenkins Credentials Plugin (can define either a key or file etc.) https://wiki.jenkins-ci.org/display/JENKINS/Credentials+Plugin

Fairly common patterns used:

1) Use the CI/CD Tool Encryption Capabilities (i.e. Jenkins, use Jenkins Credentials Plugin)

2) Store your secrets in the SCM (encrypted obviously). The problem then becomes delivering a secret securely at build time (or have it available at startup) to be able to decrypt the secrets (password, credentials, secrets, certs) that have been deployed. That is where the Secrets Management Tool (such a Vault) comes in. A Secret's Management tool will allow you to securely retrieve your secret for use in decryption of the secrets when it's needed.

3) Another way is to actually store all secrets, certs etc. outside of the SCM in the Secret Management Tool itself and retrieve them at deploy / startup time.

I would say use approach number 2. In that have your code access the file in the same way (same file path etc.) every time. The actual file you are trying to decrypt is somewhere in the working directory when it comes to the build. So having your Java Code access it shouldn't a problem as long as the code knows where to look for secrets file etc. Then use a Credentials plugin Secret to decrypt the file as an initial step in the build.

Related