Nexus Platform Plugin for Jenkins

This page gives an overview of the Nexus Platform Plugin for Jenkins and contains instructions for the IQ Server integration.

To see instructions for integrating with Repo Manager 3, click here.

To see instructions for integrating with Repo Manager 2, click here.

Table of Contents

Overview 

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 following scan patterns are set by default.  Other patterns will need to be manually included in the iqScanPatterns override.  
    • **/*.jar, **/*.war, **/*.ear, **/*.zip, **/*.tar.gz

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. NEW IN RELEASE 3.13.x
       Display Name: A name that will be displayed in places where a user can select a Nexus IQ Server instance from a list.
    2. NEW IN RELEASE 3.13.x
       Server ID: An ID that can be used to specify a Nexus IQ Server instance in pipeline builds.
    3. Server URL: The location of your IQ Server.
    4. 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.  NOTE : at a minimum, the user must have the Evaluate Applications permission, which requires them to have the correct role.
  4. By default, IQ Reports are embedded in Jenkins directly for convenience. If you preferred to only include links to the reports in your IQ Server, select the Hide embedded reports in Jenkins option.
  5. After a successful connection to IQ Server, click the Save button.
NEW IN RELEASE 3.13.x
 Multiple Nexus IQ Server instances can be configured. All existing build configurations that run policy evaluations are backwards compatible and they will use the first Nexus IQ Server in the list by default.

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 nexusPolicyEvaluation: Invoke Nexus Policy Evaluation.
    2. NEW IN RELEASE 3.13.x
       IQ Instance: Select an IQ Server that will be used to run the policy evaluation.
    3. Stage: Select Develop, Source, 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.

    4. NEW IN RELEASE 3.16.x Organization (optional): Select an organization from the list. If  automatic application creation  is enabled and the application does not exist, it will be created under the selected organization.

      If both the application and the organization IDs are provided, and the application already exists under a different organization, the evaluation process stops with an error message. This mechanism is in place to prevent accidental configurations, which could unintentionally alter the evaluation history of existing applications. 

    5. 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.  If automatic application creation is enabled, an application, that's not in the list can also be specified and an application with the specified ID will automatically be created in IQ Server.
    6. Advanced options: See the Advanced Step Options for details of each option. Use the Jenkins Pipeline Snippet Generator to help generate supported advanced options for your current plugin version.

  3. Click the Generate Pipeline Script button.
  4. Copy the generated script and paste it into the desired stage of your pipeline script. 

    Example Pipeline Script

    nexusPolicyEvaluation(
    		iqApplication: 'SampApp',
    		iqInstanceId: 'MyNexusIQServer1',
    		iqStage: 'build'
    )

    Example Pipeline Script with Scan Patterns to Override Defaults

    nexusPolicyEvaluation(
    		 iqApplication: 'SampApp',
    		 iqInstanceId: 'MyNexusIQServer1',
    		 iqScanPatterns: [[scanPattern: '**/*.js'], [scanPattern: '**/*.zip']],
    		 iqStage: 'build',
    		 iqOrganization: '55040769ec08424e84049356a3362d07'
    )

    Example Pipeline Script Overriding Most Advanced Options

    nexusPolicyEvaluation(
    		 advancedProperties: 'test=value',
    		 enableDebugLogging: true,
    		 failBuildOnNetworkError: true,
    		 iqApplication: selectedApplication('sandbox-application'),
    		 iqInstanceId: 'MyNexusIQServer1',
    		 iqModuleExcludes: [[moduleExclude: '**/module-2-exclude/module.xml'], [moduleExclude: '**/module-1-exclude/module.xml']],
    		 iqScanPatterns: [[scanPattern: '**/other/*.jar'], [scanPattern: '**/special/*.jar']],
    		 iqStage: 'build',
    		 jobCredentialsId: 'nexus-iq-server-localhost'
    )
  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 nexusPolicyEvaluation as the sample step, select the IQ instance, 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', iqInstanceId: 'MyNexusIQServer1', 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;
}

Project Step 

Add a Nexus Policy Evaluation build step to the project:

  1. In the Build section of the project configuration screen, click the Add Build Step dropdown button and then select Invoke Nexus Policy Evaluation
  2. NEW IN RELEASE 3.13.x
     IQ Instance: Select an IQ Server that will be used to run the policy evaluation.
  3. Stage: Select Develop, Source, Build, Stage 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 .

  4. NEW IN RELEASE 3.16.x Organization (optional): Select an organization from the list. If  automatic application creation  is enabled and the application does not exist, it will be created under the selected organization.

    If both the application and the organization IDs are provided, and the application already exists under a different organization, the evaluation process stops with an error message. This mechanism is in place to prevent accidental configurations, which could unintentionally alter the evaluation history of existing applications. 

  5. 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.
  6. 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.
  7. 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 plugin scans all files in the workspace. Any special non-archive files like manifests may incur special handling depending on the version of plugin used.

Each Scan Target field takes an Apache Ant styled pattern (i.e. **/*.js). Supplying custom scan targets will limit scanning to only those files matching the scan targets. Only one scan target can be placed on each line.

Modules 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 default directories that Jenkins plugin scans for module.xml files are **/sonatype-clm and **/nexus-iq . Any module.xml file located elsewhere in the scan targets will be ignored.  

Module excludes:

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.

Enable debug logging: Increase verbosity of the plugin-specific job logging to aid in diagnosing scanning problems or to verify scanning configuration.  NEW IN 3.9.20201109

Advanced properties: A number of additional parameters can be supplied to the plugin using this input field. Typically these parameters will be determined by Sonatype support.

Inspecting Evaluation Results

Once a specific build has successfully completed, a summary of the results is shown on the project screen. 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).

In addition to the summary, a historical graph is shown to indicate policy health over time.

The Application Report is accessible from the summary by clicking "view report" or "Nexus IQ Policy Evaluation" in the left-hand navigation. Additionally, a Build Report is available within Jenkins by clicking the "Nexus IQ Build Report" in the left-hand nav. This build report shows which components caused a 'warn' or 'fail' action on a particular build.



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.

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', iqInstanceId: 'MyNexusIQServer1', iqScanPatterns: [[scanPattern: 'image.tar']], iqStage: 'build'