{{announcement.body}}
{{announcement.title}}

Publishing Artifacts to Sonatype Nexus Using Jenkins Pipelines

DZone 's Guide to

Publishing Artifacts to Sonatype Nexus Using Jenkins Pipelines

In this guide, we will use Jenkins as a continuous integration server and Nexus as a build repository.

· Integration Zone ·
Free Resource

In this guide, we will use Jenkins as a continuous integration server and Nexus as a build repository.

The end goal of this guide is to create a flow, where we can build, store, organize, and monitor the compiled artifacts by Maven through our CI server.

Before we begin, make sure that you already have Jenkins up and running. In case you haven’t set up Jenkins yet, then copy the below command and run it on your Docker enabled host/machine.

Shell
 




xxxxxxxxxx
1


 
1
$ docker run -d --name jenkins-ci -p 8080:8080 jenkins/jenkins:lts


Once, Jenkins container is configured on your local/remote machine. Go to your preferred browser and open the URL http:///your-ip-addr:8080

On the very first page, Jenkins will ask you for the admin password, which you can find by running below mentioned command in your terminal:

Shell
 




xxxxxxxxxx
1


 
1
$  docker exec -i jenkins-ci cat /var/jenkins_home/secrets/initialAdminPassword
2
 
           
3
b5102c8d9fa245dbb0b8da03f504d3a5


Follow the guided steps to finish the configuration. Save the username and password securely for future use.

Installing Nexus

Nexus is a repository manager that allows you to store and retrieve artifacts. It enables you to host your built artifacts in a private and secure repo. You can always pull the Nexus Docker image using the following command:

Shell
 




xxxxxxxxxx
1
11


1
$ docker pull sonatype/nexus3
2
 
3
Using default tag: latest
4
latest: Pulling from sonatype/nexus3
5
cb3c77f9bdd8: Pull complete 
6
fd8daf2668d1: Pull complete 
7
fd1ff82b00e8: Pull complete 
8
2a05f7b573af: Pull complete 
9
Digest: sha256:6570855dfbc3eb094fe5cbbacec87aa8b91d16394dab627177e1deeebb5ac8ee
10
Status: Downloaded newer image for sonatype/nexus3:latest
11
docker.io/sonatype/nexus3:latest


Now it’s time to run downloaded sonatype/nexus on the default port 8081. Follow the below-mentioned commands: 

Shell
 




xxxxxxxxxx
1


1
$ docker run -d --name nexus_repo -p 8081:8081 sonatype/nexus3


Usually, it takes 1 to 2 minutes for the Nexus service to launch in your newly created Docker container. If you wish to follow the log to see if Nexus is up and ready, then run the following command: 

Shell
 




xxxxxxxxxx
1


 
1
$ docker logs nexus_repo -f 


In logs, you will see a message stating Started Sonatype Nexus OSS 3.20.1-01. It means your Nexus Repository Manager is ready to use. Now go to your browser and open http://your-ip-addr:8081. Find the Sign In option as shown below: 


The default username is admin, whereas to retrieve the password you need to run the following command:

Shell
 




xxxxxxxxxx
1


 
1
$ docker exec -i nexus_repo cat /nexus-data/admin.password
2
502ace93-5450-4f0d-97d2-9b3b3a88d149


And that’s it. Your Nexus Repository Manager is ready-to-use. The next step is to create a new repository.

Create a Repository in Nexus

In this step, you are going to create a Maven Hosted repository in Nexus, where your Jenkins is going to upload “build” artifacts.

Step 1:
Follow the below-mentioned steps to create a hosted repository, name it as maven-nexus-repo, which you are going to use throughout this guide.

Select maven2 (hosted) recipe from the list as shown in the below-mentioned figure:


Step 2:
On the Create Repository page:

  • Enter the name as maven-nexus-repo
  • In Version Policy, select the Mixed type of artifacts
  • Under the Hosted section, in Deployment policy, select Allow redeploy. It will allow you to deploy an application multiple times.

Step 3:
To create a new user, go to Dashboard > Server Administrator and Configuration > User > Create user. Select Local user type which happens to be the default Realm:


In the Create User page,

  1. ID: Enter the desired ID; in our case, it is jenkins-user.
  2. First Name: Enter the desired first name; in our case, it is Jenkins.
  3. Last Name: Enter the desired second name; in our case, it is User.
  4. Email: Enter your email address.
  5. Status: Select Active from your drop-down menu.
  6. Roles: Make sure that you grant the nx-admin role to your user.

In case you want more details for user creation, then click here.

With this, we are through with the setup part of Nexus Repository Manager. Let us move to Jenkins to setup Nexus there.

Install and Configure Nexus Plugins in Jenkins

Here you are going to install and configure a few plugins for Nexus in Jenkins. For this, go to Jenkins and then Dashboard > Manage Jenkins > Manage Plugins > Available and search and install Nexus Artifact Uploader and Pipeline Utility Steps.

Add Nexus Repository Manager’s user credentials in Jenkins. Go to Dashboard > Credentials > System > Global credentials (unrestricted), as shown below:


Next, set up Maven as a managed tool. Go to Dashboard > Manage Jenkins > Global Tool Configuration and find Maven. Under this section, click on the Maven Installations button and add Maven, as shown below:

Alternatively, you can also install the Maven binary directly to your container on the /var/jenkins_home directory.

Create a Jenkins Pipeline

It’s time to create a Jenkins Job. Here you are going to use Pipeline job type, named as JenkinsNexus, as shown below:

In the next page, find the Pipeline section and copy the below-mentioned script in the text area:

Shell
 




xxxxxxxxxx
1
66


1
pipeline {
2
    agent {
3
        label "master"
4
    }
5
    tools {
6
        maven "Maven"
7
    }
8
    environment {
9
        NEXUS_VERSION = "nexus3"
10
        NEXUS_PROTOCOL = "http"
11
        NEXUS_URL = "you-ip-addr-here:8081"
12
        NEXUS_REPOSITORY = "maven-nexus-repo"
13
        NEXUS_CREDENTIAL_ID = "nexus-user-credentials"
14
    }
15
    stages {
16
        stage("Clone code from VCS") {
17
            steps {
18
                script {
19
                    git 'https://github.com/javaee/cargotracker.git';
20
                }
21
            }
22
        }
23
        stage("Maven Build") {
24
            steps {
25
                script {
26
                    sh "mvn package -DskipTests=true"
27
                }
28
            }
29
        }
30
        stage("Publish to Nexus Repository Manager") {
31
            steps {
32
                script {
33
                    pom = readMavenPom file: "pom.xml";
34
                    filesByGlob = findFiles(glob: "target/*.${pom.packaging}");
35
                    echo "${filesByGlob[0].name} ${filesByGlob[0].path} ${filesByGlob[0].directory} ${filesByGlob[0].length} ${filesByGlob[0].lastModified}"
36
                    artifactPath = filesByGlob[0].path;
37
                    artifactExists = fileExists artifactPath;
38
                    if(artifactExists) {
39
                        echo "*** File: ${artifactPath}, group: ${pom.groupId}, packaging: ${pom.packaging}, version ${pom.version}";
40
                        nexusArtifactUploader(
41
                            nexusVersion: NEXUS_VERSION,
42
                            protocol: NEXUS_PROTOCOL,
43
                            nexusUrl: NEXUS_URL,
44
                            groupId: pom.groupId,
45
                            version: pom.version,
46
                            repository: NEXUS_REPOSITORY,
47
                            credentialsId: NEXUS_CREDENTIAL_ID,
48
                            artifacts: [
49
                                [artifactId: pom.artifactId,
50
                                classifier: '',
51
                                file: artifactPath,
52
                                type: pom.packaging],
53
                                [artifactId: pom.artifactId,
54
                                classifier: '',
55
                                file: "pom.xml",
56
                                type: "pom"]
57
                            ]
58
                        );
59
                    } else {
60
                        error "*** File: ${artifactPath}, could not be found";
61
                    }
62
                }
63
            }
64
        }
65
    }
66
}


Let’s break down the above-mentioned parameters bit by bit:

  • NEXUS_VERSION: Here, we have to mention the exact version of Nexus, which can be nexus2 or nexus3. In our case, it is latest version of nexus3.
  • NEXUS_PROTOCOL: For this guide we have used HTTP protocol, although, in case of production, you will have to use HTTPS.
  • NEXUS_URL: Add your IP address and port number, where you are running Nexus. Make sure that you add Nexus instance details without mentioning protocols, i.e., https or http.
  • NEXUS_CREDENTIAL_ID: Enter the user ID, which you previously created in Jenkins, which in our case is nexus-user-credentials.
  • Project Git: Under stages, we used https://github.com/javaee/cargotracker

As you are through with the Pipeline set up, it’s time to Build our project. Go to the JenkinsNexus project job page and click Build Now. As this is your first build, it is going to take some time, so sit tight.

Once build is a success, in your Jenkins Console Output, you will see something like this:

Whereas, in your Nexus Repository Manager, you would see something similar to this:

Conclusion

A systematic way to disturb the project’s artifact is critical for any organization. With the help of Jenkins Pipeline and Nexus Repository Manager, you can centralize artifact repo, which ultimately reduces the efforts of reproducing build time as well as switch CI tools without worrying about migrating our artifacts.

Nexus can be configured with cloud storage services like AWS S3 and Google Cloud Storage as well, which gives you additional freedom and delivery application without any hassle of storage.

Now, where next? Well, it's really up to you. 


This article was originally posted on https://appfleet.com/

Topics:
cicd, cicd pipeline, cloud native, docker, jenkins, nexus, sonatype

Published at DZone with permission of Sudip Sengupta . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}