Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass credentials to maven from Jenkins

Tags:

maven

jenkins

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.

like image 958
CDO Avatar asked Aug 08 '19 20:08

CDO


1 Answers

By injecting Jenkins credentials into your environment, and then passing those credentials to maven, you can access private repos using Jenkins credentials.

Steps:

  1. Create a new pair of Jenkins credentials if you haven't already (I am using the id "test-creds")
  2. 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}'
    }
  1. In your settings.xml file, reference these variables:
    <servers>
        <server>
            <id>ServerID</id>
            <username>${server.username}</username>
            <password>${server.password}</password>
        </server>
    </servers>
  1. If you need to specify a settings.xml file, you can use the -s or -gs flag in your maven command.
like image 71
CDO Avatar answered Oct 23 '22 11:10

CDO