CDO
CDO

Reputation: 352

Pass credentials to maven from 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.

Upvotes: 9

Views: 19342

Answers (3)

CDO
CDO

Reputation: 352

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.

Upvotes: 11

Hui Tan
Hui Tan

Reputation: 11

from Config File Provider pageThis only works with freestyle or maven jobs. Will not work on multibranch pipeline. Refer to the config file provider plugin documentation here

Upvotes: 1

Gleb Yan
Gleb Yan

Reputation: 431

There is a better way how to solve this task using the Config File Provider and Credentilals Jenkins plugins. Just create the maven settings.xml config file and inject the server credentials into it.

Steps:

  1. Create a new pair of Jenkins credentials if you haven't already (select kind "username and password").
  2. Use the config file provider plugin to create the new maven settings.xml file. Just copy your existing maven.xml file into the "content" field and remove section <servers>. You don't need it in Jenkins.
  3. In the "Server credentials" block press the "Add" button. Full up the server name and select appropriate credentials for it. The <server> section will automatically be added to your settings.xml file in runtime. You may add more than one server.
  4. Use the maven files in the pipeline:
stage('Publish to nexus')
    withMaven(mavenSettingsConfig: 'the name of your configuration file in jenkins'){
        sh mvn clean deploy
    }

Upvotes: 4

Related Questions