Issue
I have a node running Jenkins that builds code with maven. The Jenkins job is a declarative pipeline script. Maven needs to download dependencies from private repositories which require credentials to access. The credentials are stored in the Jenkins credential manager.
How can I pass these credentials to maven so that maven can correctly download dependencies from private repos using these credentials.
Solution
By injecting Jenkins credentials into your environment, and then passing those credentials to maven, you can access private repos using Jenkins credentials.
Steps:
- Create a new pair of Jenkins credentials if you haven't already (I am using the id "test-creds")
- Using the instructions from this question : How to pass Maven settings via environmental vars. Around the maven command that requires the credentials, use a "withCredentials" block. And then pass those credentials in to maven.
withCredentials([usernamePassword(credentialsId: 'test-creds', passwordVariable: 'PASSWORD_VAR', usernameVariable: 'USERNAME_VAR')])
{
sh 'mvn clean install -Dserver.username=${USERNAME_VAR} -Dserver.password=${PASSWORD_VAR}'
}
- In your settings.xml file, reference these variables:
<servers>
<server>
<id>ServerID</id>
<username>${server.username}</username>
<password>${server.password}</password>
</server>
</servers>
- If you need to specify a settings.xml file, you can use the
-s
or-gs
flag in your maven command.
Answered By - CDO