Nexus Platform Plugin for Jenkins

Features

Nexus Platform Plugin for Jenkins is a Jenkins 2.x plugin that integrates via Jenkins Pipeline or Project steps with Sonatype Nexus Repository Manager and Sonatype Nexus IQ Server.

The main features are:

Nexus Platform Plugin for Jenkins is only compatible with Jenkins versions 2.x. Support for Jenkins 1.x is available using a now deprecated plugin.

Installation

Install Using Jenkins Plugin Manager

  1. Login to Jenkins as an administrator.
  2. Select Manage Jenkins from the left-navigation menu.
  3. Select Manage Plugins from the list of configuration options to open the Jenkins Plugin Manager.
  4. In the Plugin Manager window, select the Available tab and enter "nexus platform" in the Filter: search box.
  5. Select the Install checkbox next to Nexus Platform plugin and then click either the Install without restart or Download now and install after restart button:

A message displays on the screen when the Nexus Platform plugin has successfully installed.

Install Using Alternative Methods

The latest and archived versions of the plugin can be downloaded directly from https://updates.jenkins.io/download/plugins/nexus-jenkins-plugin/ and then installed using the Jenkins CLI or advanced methods.

Using Nexus Platform Plugin Build Steps

Regardless of whether your builds are using Pipelines or Projects, features of this plugin are implemented as build steps.

Unless otherwise stated in this document:

  • Pipeline refers to both Declarative and Scripted Jenkins Pipelines
  • Project refers to a Jenkins item, such as a Freestyle, Multi-configuration, or Maven projects, that allows selecting an explicit build step from a drop-down menu and filling in form field values inside the build configuration. 

The step user interface is identical for Jenkins Projects Build configuration and in the Pipeline Snippet Generator.

The available step names for the latest version of the plugin are listed on the Nexus Platform Plugin Steps Reference page. These include:

  • Invoke Nexus Policy Evaluation

  • Nexus Repository Manager Publisher

  • Associate Tag (Nexus Repository Manager 3.x)
  • Create Tag (Nexus Repository Manager 3.x)
  • Move Components (Nexus Repository Manager 3.x)
  • Delete Components (Nexus Repository Manager 3.x)

Defining Steps for Pipeline

  1. In the Pipeline section of a Pipeline project configuration screen, open the Snippet Generator by clicking the Pipeline Syntax link.
  2. In the Steps section of the Snippet Generator window, select one of the Nexus Platform Plugin defined steps. 
  3. After filling in the step field values, you can copy the generated snippet into your pipeline script.

Defining Steps for Projects

  1. In the Build section of your project configuration screen, click the Add Build Step drop-down and select a Nexus Platform Plugin step from the list.
  2. Fill in the step field values and save your project.

Nexus IQ Server Integration

Nexus Platform Plugin for Jenkins scans a build workspace for components, create a summary file about all the components found, and then submits that file to IQ Server for a detailed policy evaluation. A report is generated containing detailed analysis of security and license information and a summary of that report is sent back to the Jenkins server to be included in the build results. The link to the detailed evaluation report can be followed from the Jenkins UI.

Connecting Jenkins to IQ Server

  1. Select Manage Jenkins from the left-navigation menu.
  2. Select Configure System from the list of configuration options.
  3. In the Sonatype Nexus section, select Nexus IQ Server from the Add Nexus IQ Server dropdown menu and then enter the following:
    1. Server URL: The location of your IQ Server.
    2. Credentials: Select the Add button to enter your IQ Server username and password using the Jenkins Provider Credentials: Jenkins modal window. Once added, select your IQ Server username and password from the Credentials dropdown list and click the Test Connection button.
  4. After a successful connection to IQ Server, click the Save button.

Only one IQ Server instance can be configured.

Evaluating Build Output Against a Policy

Pipeline Step

Jenkins pipelines allow for policy evaluation at any point during the build, providing a way to gain a bill of materials of components that may not exist during final delivery. In addition, this allows for a policy gate to be set anywhere along the build and delivery process.

Use the following steps to add a Nexus Policy Evaluation build step to a pipeline build:

  1. In the Pipeline section of the project configuration screen, click the Pipeline Syntax link.
  2. In the Steps section of the Snippet Generator window, select the following:
    1. Sample Step: Select NexusPolicyEvaluator: Nexus Policy Evaluation.
    2. Stage: Select BuildStage ReleaseRelease, or Operate. This controls the stage the policy evaluation is run against on the IQ Server. Only the stages you are licensed to appear in the list.

    Depending on how your policies are configured, this may impact warning and fail actions.

    1. Application: Select an application from the list of available IQ Server applications. This determines the policy elements (policies, labels, and license threat groups) to associate with this build and is managed via the IQ Server.  An application can also be specified that is not in the list. If automatic application creation is enabled, an application with the specified ID will automatically be created if it does not already exist in IQ Server.
    2. Advanced options: See the Advanced Step Options section below.
  3. Click the Generate Pipeline Script button.
  4. Copy the generated script and paste it into the desired stage of your pipeline script. See an example pipeline script below:

    nexusPolicyEvaluation iqApplication: 'SampApp', iqStage: 'build'
  5. Complete your pipeline build as desired and click Save.

Return Value from Pipeline Build

Utilizing the Nexus IQ for Jenkins plugin provides full component intelligence and the ability to run policy against your application. Jenkins pipelines let you invoke a build step as part of the build process and use the results for complex workflows. For example, objects returned from a build pipeline step can be used to provide feedback in-application about the process of an evaluation. In the following example, we’ll setup a pipeline build that uses results of a policy evaluation to push data to a GitHub pull request.

First, start a new Jenkins pipeline job for a Maven build. Next, add a build stage that calls Maven clean package, wrapped in a few GitHub status updates. For this example, we’re going to send an update pending when we start the build and have it update the status to indicate if the build succeeded:

stage('Build') {
  postGitHub commitId, 'pending', 'build', 'Build is running'

  try {
    sh  "${mvnHome}/bin/mvn clean package"
    postGitHub commitId, 'success', 'build', 'Build succeeded'
  } catch (error) {
    postGitHub commitId, 'failure', 'build', 'Build failed'
    throw error
  }
}


Next, we’ll add a small helper that sends a cURL to the GitHub API to update the status. To do this, set and declare the  gitHubApiToken  and  project  variables and then create the following function:

def postGitHub(commitId, state, context, description, targetUrl) {
  def payload = JsonOutput.toJson(
    state: state,
    context: context,
    description: description,
    target_url: targetUrl
  )
  sh "curl -H \"Authorization: token ${gitHubApiToken}\" --request POST --data '${payload}'
  https://api.github.com/repos/${project}/statuses/${commitId} > /dev/null"
}

After the build, we need to run a Nexus Lifecycle Analysis to determine what the policy evaluation results are. This will let GitHub know Nexus Lifecycle Analysis is running and then do the policy evaluation. The easiest way to do this is using the Jenkins Pipeline Syntax helper to generate a Groovy script.

Click the Pipeline Syntax link on your build configuration screen to open the Pipeline Syntax helper. Select NexusPolicyEvaluator as the sample step, select the stage and application you’d like to evaluate against, and then click Generate Pipeline Script. Copy the script and paste it into your pipeline script.

In addition to calling the evaluation, you will want to do something with the evaluation results. To do this, set a  policyEvaluation  variable to the result. Like with the build, you’ll want to look whether the build result is a failure or not to determine how to update your GitHub pull request. You can also add a link to the Application Composition Report. Having this available in your pull request lets you go directly to the evaluation, see why it failed, and perform remediation. An example Nexus Lifecycle Analysis script is shown below:

stage('Nexus Lifecycle Analysis') {
  postGitHub commitId, 'pending', 'analysis', 'Nexus Lifecycle Analysis is running'

  try {
    def policyEvaluation = nexusPolicyEvaluation iqApplication: 'webgoat', iqStage: 'build'
	postGitHub commitId, 'success', 'analysis', 'Nexus Lifecycle Analysis succeeded', "${policyEvaluation.applicationCompositionReportUrl}"
  } catch (error) {
    def policyEvaluation = error.policyEvaluation
    postGitHub commitId, 'failure', 'analysis', 'Nexus Lifecycle Analysis failed', "${policyEvaluation.applicationCompositionReportUrl}"
    throw error
  }
}

Save your pipeline and then run the build. When the build has completed, you should see successful steps for Build and Nexus Lifecycle Analysis. Going to your GitHub pull request, you will see the successful checks and you can click the details link to view your report and address alerts or reevaluate policy.

When you access various properties on objects in a pipeline build, Jenkins has security permissions that restrict unauthorized use. In Manage Jenkins navigate to In-process Script Approval and approve scripts (ie application composition report, affected component count) for the analysis to run. Lack of script approvals will result in errors like:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to
use method com.sonatype.nexus.api.iq.ApplicationPolicyEvaluation getApplicationCompositionReportUrl

In the above example, we utilized cURL to interact with the GitHub API and provide analysis feedback to GitHub. Many companies use GitHub for code review, and noting the status of CI builds in your pull request is a powerful analysis tool. In addition to GitHub, you can use the object returned from the policy evaluation with almost anything that provides an interactive API or other Jenkins plugins.

Want to see this in action? Here is a video example.

nexusPolicyEvaluation Pipeline step returns a evaluation result data model from which your Pipeline script may read additional information:

public class ApplicationPolicyEvaluation {
        private final List<PolicyAlert> policyAlerts;
        private final int affectedComponentCount;
        private final int criticalComponentCount;
        private final int severeComponentCount;
        private final int moderateComponentCount;
        private final String applicationCompositionReportUrl;
}

public class PolicyAlert {
        private final PolicyFact trigger;
        private final List<? extends Action> actions;
}

public class Action {
        private final String actionTypeId;
        private final String target;
        private final String targetType;
}

public class PolicyFacts {
        private final String policyId;
        private final String policyName;
        private final int threatLevel;
}

Evaluating Docker Images

On a build agent with docker installed, the Docker CLI can be invoked using batch or shell scripts from a build pipeline. Save a Docker image to the workspace as a tarred archive and configure a nexusPolicyEvaluation task to evaluate the tarred archive. Make certain to customize the scan targets to include images stored with the tar extension.

sh "docker save -o ${env.WORKSPACE}/image.tar image"
nexusPolicyEvaluation iqApplication: 'appId', iqScanPatterns: [[scanPattern: 'image.tar']], iqStage: 'build'

Project Step

Add a Nexus Policy Evaluation build step to project:

  1. In the Build section of the project configuration screen, click the Add Build Step dropdown button and then select Nexus Policy Evaluation
  2. Stage: Select BuildStage ReleaseRelease, or Operate. This controls the stage the policy evaluation is run against on the IQ Server. Only the stages enabled by your IQ Server license appear in the list.

    The severity of the IQ Server Policy Actions for a Stage is intended to influence the final build result. A Warn action equates to an UNSTABLE build. A Fail action equates to a FAILURE. The build result can also be overridden in a Pipeline .

  3. Application: Select an application from the list of available IQ Server applications. This determines the policy elements (policies, labels, and license threat groups) to associate with this build and is managed via the IQ Server. An application can also be specified that is not in the list. If automatic application creation is enabled, an application with the specified ID will automatically be created if it does not already exist in IQ Server.

  4. Advanced options: Click the Advanced... button to view the advanced options.  Note that when using custom scan targets only one target is allowed per line.
  5. Complete the rest of your project configuration and click Save.

Advanced Step Options

There are various advanced options that allow you to configure your policy evaluation.

Scan Targets: By default the Jenkins plugin evaluates Java artifacts (e.g. jar, war) and archives (e.g. zip, tar.gz):

"**/*.jar", "**/*.war", "**/*.ear", "**/*.zip", "**/*.tar.gz"

Supplying Scan Targets can customize this allowing for scanning of other files such as JavaScript (.js). Scan Targets takes Apache Ant styled patterns (i.e. **/*.js).

Note: Only one scan target can be placed on each line.

Module excludes in workspace: The Sonatype CLM for Maven has an index goal which can be used to create a module.xml file with all an application's components. By default, any module.xml file within it's default directory will be scanned and evaluated for policy evaluation. The Module Excludes feature can be used to exclude any of these module.xml files from evaluation. Module Excludes takes Apache Ant styled patterns (i.e. **/sonatype-clm/module.xml).

Fail build when unable to communicate with IQ Server: Enabling this option will fail the build when the IQ Server is unreachable.

Use job specific credentials: This allows overriding the global credential configuration with job specific authentication credentials.

Inspecting Evaluation Results

Once a specific build has successfully completed, a link to the Application Composition Report is shown on the project screen. Clicking on the link directs you to a display of the report within the IQ Server. The three boxes (red, orange, and yellow) located below the link give you counts for policy violations and are based on the associated severities (critical, severe, and moderate).

If you are looking for previous report results, navigate to a specific build in the Build History. If you previously scanned the application during that specific build, a new item is shown in the left menu, titled Application Composition Report. Following this link takes you to the report on the IQ Server.

Repository Manager 3 Integration

The Nexus Platform Plugin for Jenkins provides the powerful abilities needed to orchestrate your organization's build and release pipelines while also enabling integration and orchestration of the staging functionality in Nexus Repository Manager Pro. Features include:

  • publishing tagged build outputs to repository manager
  • creating and associating tags to components
  • moving / promoting tagged components through a series of staging repositories (e.g. dev, test, qa)
  • deleting tagged components as needed during post release cleanup activities

Compatibility

  • For staging and tagging functionality, Nexus Repository Manager Pro 3.13 or newer is required along with the Jenkins Plugin 3.3.20181207-134824.d240aa3 or newer.
  • For component upload functionality, Nexus Repository Manager 3.12.1 or newer is required along with the Jenkins Plugin 3.3.20181207-134824.d240aa3 or newer.

Connecting Jenkins to Repository Manager 3

Connect Jenkins to connect to Nexus Repository Manager 3:

  1. Select Manage Jenkins from the Dashboard’s left-navigation menu.
  2. Select Configure System from the list of configuration options.
  3. In the Sonatype Nexus section, click the Add Nexus Repository Manager Server dropdown menu and then select Nexus Repository Manager 3.x Server. Enter the following:
    1. Display Name: Name of the server to show when selecting Nexus Repository Manager instances for build jobs.
    2. Server ID: A unique ID used to reference Nexus Repository Manager in Build Pipeline scripts. It should be alphanumeric without spaces.
    3. Server URL: Location of your Nexus Repository Manager server.
    4. Credentials: Select the Add button to enter your Nexus Repository Manager username and password using the Jenkins Provider Credentials: Jenkins modal window. Once added, select your Nexus Repository Manager username and password from the Credentials dropdown list.
  4. Click the Test Connection button.
  5. After a successful connection to Nexus Repository Manager, click the Save button.

Repeat the above process for each individual repository manager server instance.

Publish / Deploy Components

The following repository formats are supported by the publisher:

  • Maven 2 release repositories

Publishing and Tagging Maven 2 release versioned components

  1. In a Build step section of a Project configuration screen, select Nexus Repository Manager Publisher from the list. Enter the following parameters:
    1. Nexus Instance: Select the display name of a repository manager 3 instance that was pre-configured in Jenkins global configuration.
    2. Nexus Repository: Select a repository that has a release repository policy and allows for artifact uploads. If a snapshot repository is selected as the target for publishing, the build step will fail. Use the maven-deploy-plugin for snapshot builds.
    3. Tag: Enter the tag name to associate with the uploaded component. If a tag with the specified name does not exist an attempt will be made to create the tag during the upload process. 

      Tagging is only available when using a Nexus Repository Manager 3 Pro instance

    4. Packages: Select packages to publish to Nexus Repository Manager during your freestyle build. For this example, use the Add Package dropdown to select a Maven Package
  2. Once you have finished configuring the step as desired, click Save.
  3. Launch a build for your project. When the build completes, you should see output similar to the following confirming the upload succeeded:

        

If at the time of publishing the tag specified does not exist, the plugin will create the tag prior to publishing so the tagging action can complete as intended.

Tagging Components

Tagging is not available when using a Nexus Repository Manager 3 OSS instance

Create Tag in Repository Manager

  1. In the Build step section of a Project configuration screen, click the Add Build Step dropdown button and then select Create Tag (Nexus Repository Manager 3.x). Enter the following parameters:
    1. Nexus Instance: Select the display name of a repository manager instance that was pre-configured in Jenkins global configuration.
    2. Tag Name: The name to be given to the created tag (e.g. build-xyz)
    3. Tag Attributes File( Optional) Additional attributes to include with the tag.  Examples could be details about the build, version, or some other detail relevant to your organization's release process or pipeline.
    4. Tag Attributes  (JSON): (Optional) Similar to the Tag Attributes File option, this field provides a means for specifying additional attributes to include with the tag as JSON within the Jenkins UI.

  2. Once you have finished configuring the step as desired, click Save.
  3. Launch a build for your project. When the build completes, you will see output similar to the following:

Associate Tag with Components

  1. In the Build step section of the project configuration screen, click the Add Build Step dropdown button and then select Associate Tag (Nexus Repository Manager 3.x). Enter the following parameters:
    1. Nexus Instance: Select the display name of a repository manager instance that was pre-configured in Jenkins global configuration.
    2. Tag Name: The name to be given to the created tag (e.g. build-xyz)
    3. Search Criteria: One or more Key / Value pairs to search repository manager for the components to associate with the tag. 
      The valid Key names are the supported search parameters listed for the Associate Tags REST API
      Click the Add button in this section to add a new key value search criteria pair.
      Click the red X icon within each key value pair section to delete a pair.

  2. Once you have finished configuring the step as desired, click Save.
  3. Launch a build for your project. When the build completes, you will see output similar to the following:

Staging Workflow

Staging is not available when using a Nexus Repository Manager 3 OSS instance

Move (Promote) Components

  1. In the Build step section of the configuration screen, click the Add Build Step dropdown button and then select Move Components (Nexus Repository Manager 3.x). Enter the following parameters:
    1. Nexus Instance: Select the display name of a repository manager instance that was pre-configured in Jenkins global configuration.
    2. Destination Repository: Select the hosted repository to which the components associated with the tag should be moved. 
    3. Tag Name: The tag to be used to identify the set of components to move. It is assumed a tag with the name specified in this field already exists, if it does not the move action will fail.
  2. Once you have finished configuring the step as desired, click Save.
  3. Launch a build for your project. When the build completes, you will see output similar to the following which details the components that were moved:

Delete Components

  1. In the Build step section of the configuration screen, click the Add Build Step dropdown button and then select Delete Components (Nexus Repository Manager 3.x). Enter the following parameters:
    1. Nexus Instance: Select the display name of a repository manager instance that was pre-configured in Jenkins global configuration.
    2. Tag Name: The tag to be used to identify the set of components to delete. It is assumed a tag with the name specified in this field already exists, if it does not the delete action will fail.
  2. Once you have finished configuring the step as desired, click Save.
  3. Launch a build for your project. When the build completes, you will see output similar to the following which details the components that were deleted:

Pipeline Staging Workflow Example

Pipeline builds allow for precise control over your build process. In this section, we will continue the examples from above and demonstrate usage of Jenkins to orchestate the Nexus Repository Manager Pro staging features within a pipeline to publish, move and delete components. The pipeline script will:

  • Create a tag named build-125 and publish (and tag with build-125fancyWidget version 1.1 to the maven-dev repository.
  • Move fancyWidget components tagged with build-123 to the maven-test repository.
  • Delete fancyWidget components tagged with build-120.

For the sake of this example we uploaded oldFancyWidget version 1.0 to the maven-releases repository and tagged the component with build-120. We have also created a two additional Maven hosted repositories for use in this example, maven-dev and maven-test.

The steps that follow will create the script described above: 

  1. To start, create a pipeline project by clicking the New Item link on the Jenkins Dashboard. 
  2. Give the project a name and click OK to continue with the configuration. 

  3. Pipeline jobs allow you to configure the job via a Groovy script. The script is editable in the Pipeline section.
    In the Pipeline section of the configuration screen, we will add several placeholders to get us started. Modify the script to contain following: 

    node {
        echo 'Staging Components...'
        
        stage ('Creating build tag') {
        }
        stage ('Publishing') {
        }
        stage ('Move') {
        }
        stage ('Delete') {
        } 
    }

    When complete the Pipeline section should look similar to the following:

    At this point, the build script contains placeholders for creating a tag, publishing (and tagging) a component, moving components by tag, and deleting components by tag. In the following steps, each of these placeholders will be populated with the appropriate pipeline script.

  4. First, we'll populate the Creating build tag stage.

  5. Click the Pipeline Syntax link located below the Script textbox.
  6. In the Steps section of the Snippet Generator window, select/enter the following:
    1. Sample Step: Select create Tag: Create Tag (Nexus Repository Manager 3.x).
    2. Nexus Instance: Select the display name set in global configuration.
    3. Tag Name: enter build-125.
    4. Attributes: Click the  Advanced...  button to add some additional attributes. In the text box enter {"createdBy": "JohnSmith"}.

  7. Click the Generate Pipeline Script button. An example pipeline script is shown below:

    createTag nexusInstanceId: 'nx3', tagAttributesJson: '{"createdBy": "JohnSmith"}', tagName: 'build-125'

  8. Copy the generated script and paste it into the Creating build tag stage of your pipeline script.
  9. Completing the Snippet Generator is very similar to completing the Freestyle Build Step configuration.  Repeat Steps 7 and 8 for the PublishingMove, and Delete stages in your pipeline script using the following inputs:
    1. Publishing stage 
       
      The generated pipeline script shoud look similar to the following:

      nexusPublisher nexusInstanceId: 'nx3', nexusRepositoryId: 'maven-releases', packages: [[$class: 'MavenPackage', mavenAssetList: [[classifier: '', extension: '', filePath: '/Users/johnsmith/dev/fancyWidgetProject/fancyWidget.jar']], mavenCoordinate: [artifactId: 'fancyWidget', groupId: 'com.mycompany', packaging: 'jar', version: '1.1']]], tagName: 'build-125'
    2. Move stage 
       
      The generated pipeline script shoud look similar to the following:

      moveComponents destination: 'maven-test', nexusInstanceId: 'nx3', tagName: 'build-123'
    3. Delete stage 
       
      The generated pipeline script shoud look similar to the following:

      deleteComponents nexusInstanceId: 'nx3', tagName: 'build-120'
  10. When we add all the generated scripts into the pipeline configuration window, the completed script should look similar to the following (depending on any changes you may have made to the inputs):

    node {
        echo 'Staging Components...'
        
        stage ('Creating build tag') {
            createTag nexusInstanceId: 'nx3', tagAttributesJson: '{"createdBy" : "JohnSmith"}', tagName: 'build-125'
        }
        stage ('Publishing') {
            nexusPublisher nexusInstanceId: 'nx3', nexusRepositoryId: 'maven-releases', packages: [[$class: 'MavenPackage', mavenAssetList: [[classifier: '', extension: '', filePath: '/Users/johnsmith/dev/fancyWidgetProject/fancyWidget.jar']], mavenCoordinate: [artifactId: 'fancyWidget', groupId: 'com.mycompany', packaging: 'jar', version: '1.1']]], tagName: 'build-125'
        }
        stage ('Move') {
            moveComponents destination: 'maven-test', nexusInstanceId: 'nx3', tagName: 'build-123'
        }
        stage ('Delete') {
            deleteComponents nexusInstanceId: 'nx3', tagName: 'build-120'
        } 
    }
  11. Launch a build for your project.
  12. Once the job has completed you should see something similar to the following in the Jenkins output console (some additional Jenkins boilerplate logging has been removed for brevity):

    Running on Jenkins in /Users/jbryan/.jenkins/workspace/fullPipeline
    Staging Components...
    Successfully created tag: '{"name":"build-125","attributes":{"createdBy":"JohnSmith"}}'
    
    Uploading Maven asset with groupId: com.mycompany artifactId: fancyWidget version: 1.1 To repository: maven-dev
    Successfully Uploaded Maven Assets
    
    Move successful. Destination: 'maven-test' Components moved:
    (group: com.mycompany, name: fancyWidget, version: 1.0)
    
    Delete successful. Components deleted:
    (group: com.mycompany, name: oldFancyWidget, version: 1.0)
    
    Finished: SUCCESS

Repository Manager 2 Integration

Connecting Jenkins to Repository Manager 2

Use the following instructions to configure Jenkins to connect to Nexus Repository Manager 2:

  1. Select Manage Jenkins from the Dashboard’s left-navigation menu.
  2. Select Configure System from the list of configuration options.
  3. In the Sonatype Nexus section, click the Add Nexus Repository Manager Server dropdown menu and then select Nexus Repository Manager 2.x Server. Enter the following:
    1. Display Name: Name of the server you want shown when selecting Nexus Repository Manager instances for build jobs.
    2. Server ID: A unique ID used to reference Nexus Repository Manager in Build Pipeline scripts. It should be alphanumeric without spaces.
    3. Server URL: Location of your Nexus Repository Manager server.
    4. Credentials: Select the Add button to enter your Nexus Repository Manager username and password using the Jenkins Provider Credentials: Jenkins modal window. Once added, select your Nexus Repository Manager username and password from the Credentials dropdown list.
  4. Click the Test Connection button.
  5. After a successful connection to Nexus Repository Manager, click the Save button.

Jenkins Tool Configuration for Maven (Optional)

Nexus Repository Manager for Jenkins can upload artifacts to a Maven repository without a Maven installation, however the examples provided in this section use Maven to build in a project. A Maven installation must be configured in Jenkins for these examples to work.

To configure a Maven installation:

  1. Select Manage Jenkins from the left-navigation menu.
  2. Select Global Tool Configuration from the list of configuration options.
  3. In the Maven section, click the Maven Installations… button.
  4. Configure a Maven installation. An example configuration is shown below:

After a completed installation and global configuration of Jenkins, you are ready to configure a build-step invocation as part of a specific job.

Publish / Deploy Components

Pipeline Step

Pipeline builds allow for precise control and configuration over your build process.

  1. To start, create a pipeline project by clicking the New Item link on the Jenkins Dashboard. 
  2. Give the project a name and click OK to continue with the configuration.

    Pipeline jobs allow you to configure the job via a Groovy script. The script is editable in the Pipeline section. In this example we will use the sample Github + Maven script.

  3. In the Pipeline section of the configuration screen, click the try sample Pipeline... dropdown, and then select Github + Maven:
  4. Below the Results stage, add a new placeholder Nexus Repository Manager Publish stage to the build pipeline script. An example is shown here:

    stage( 'Publish' ) {

    }

    The Nexus Repository Manager Publisher build step should occur after the build so the binaries are available for upload. For best reporting during the build process, the publish step should exist in its own stage below the Results stage.

  5. Click the Pipeline Syntax link located below the Script textbox.
  6. In the Steps section of the Snippet Generator window, select the following:
    1. Sample Step: Select NexusPublisher: Nexus Repository Manager Publisher.
    2. Nexus Instance: Select the display name set in global configuration.
    3. Nexus Repository: Select a repository that has release repository policy and allows for artifact uploads.
    4. Packages: Select packages to publish to Nexus Repository Manager during your pipeline build. For this example, use the Add Package dropdown to select a Maven Package.
  7. Click the Generate Pipeline Script button. An example pipeline script is shown below:

    nexusPublisher nexusInstanceId:  'localNexus' , nexusRepositoryId:  'releases' , packages: [[$ class 'MavenPackage' , mavenAssetList: [[classifier:  '' , extension:  '' , filePath:  'war/target/jenkins.war' ]], mavenCoordinate: [artifactId:  'jenkins-war' , groupId:  'org.jenkins-ci.main' , packaging:  'war' , version:  '2.23' ]]]

  8. Copy the generated script and paste it into the previously added publish stage of your pipeline script.
  9. Complete your pipeline build as desired and click Save.
  10. Launch a build for your project.
  11. In Nexus Repository Manager, any artifact selected in Packages will be available in the selected repository. The following example shows the Jenkins war is now available in the Releases repository:

Project Step

The freestyle build job is a flexible and configurable option, and can be used for any type of project.

  1. To start, create a freestyle project by clicking the New Item link on the Jenkins Dashboard. 
  2. Give the project a name and click OK to continue with the configuration.
  3. In the Build section of the configuration screen, click the Add Build Step dropdown button and then select Nexus Repository Manager Publisher. Enter the following parameters:
    1. Nexus Instance: Select the display name set in global configuration.
    2. Nexus Repository: Select a repository that has release repository policy and allows for artifact uploads.
    3. Packages: Select packages to publish to Nexus Repository Manager during your freestyle build. For this example, use the Add Package dropdown to select a Maven Package. 
  4. Complete your freestyle build as desired and click Save.
  5. Launch a build for your project. When the build completes, you will see output similar to the following:
  6. In Nexus Repository Manager, any artifact selected in Packages will be available in the selected repository. The following example shows the Jenkins war is now available in the Releases repository: