Jenkins common project construction tool integration 01 Maven

Integration of common project construction tools

The front-end packaging tools generally use npm

 

Java project builder

Initialize a springboot project https://start.spring.io/

When maven goes to package, there will be an xml file called POM xml file, which defines the dependencies of the project through various structured data.

This is a process of generating maven test projects

 

Maven

Official website: http://maven.apache.org/download.cgi Maven is a project build dependency management tool. Usually there is a POM in the root directory of the project XML file (this file is used to define the dependent package information and build configuration of the project)

What we often have to do is how to package in the assembly line

 

Maven installation configuration

maven also relies on JDK, so you need to use Java first_ Home configured

[root@jenkins-master ~]# java -version
openjdk version "1.8.0_282"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_282-b08)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.282-b08, mixed mode)

[root@jenkins-master ~]# tail -n6 /etc/profile
export JAVA_HOME=/usr/local/jdk8
export PATH=$JAVA_HOME/bin:$PATH
export GROOVY_HOME=/usr/local/groovy-3.0.7
export PATH=$GROOVY_HOME/bin:$PATH
export M2_HOME=/usr/local/apache-maven-3.8.1
export PATH=$M2_HOME/bin:$PATH
### download

wget  https://mirrors.bfsu.edu.cn/apache/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.tar.gz
tar zxf apache-maven-3.8.1-bin.tar.gz -C /usr/local/
cd /usr/local/apache-maven-3.8.1/
pwd  /usr/local/apache-maven-3.8.1


### Configure environment variables
vi /etc/profile
export M2_HOME=/usr/local/apache-maven-3.8.1
export PATH=$M2_HOME/bin:$PATH
source /etc/profile


### verification

mvn -v
Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)
Maven home: /usr/local/apache-maven-3.8.1
Java version: 1.8.0_282, vendor: AdoptOpenJDK, runtime: /usr/local/jdk8u282-b08/jre
Default locale: en_US, platform encoding: ANSI_X3.4-1968
OS name: "linux", version: "4.18.0-80.el8.x86_64", arch: "amd64", family: "unix"

Create a project in gitlab

If there is a local code, you can pass it on

Go to this directory and upload the code

[root@jenkins-master ~]# cd devops-maven-service-master
[root@jenkins-master devops-maven-service-master]# ls
Jenkinsfile  mvnw  mvnw.cmd  pom.xml  src

[root@jenkins-master devops-maven-service-master]# git init
Initialized empty Git repository in /root/devops-maven-service-master/.git/
[root@jenkins-master devops-maven-service-master]# git remote add origin http://139.198.170.122:81/root/devops-maven-service.git
[root@jenkins-master devops-maven-service-master]# git add .
[root@jenkins-master devops-maven-service-master]# git commit -m "Initial commit"
[master (root-commit) 0b12b52] Initial commit
 11 files changed, 816 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 .mvn/wrapper/MavenWrapperDownloader.java
 create mode 100644 .mvn/wrapper/maven-wrapper.jar
 create mode 100644 .mvn/wrapper/maven-wrapper.properties
 create mode 100644 Jenkinsfile
 create mode 100755 mvnw
 create mode 100644 mvnw.cmd
 create mode 100644 pom.xml
 create mode 100644 src/main/java/com/example/demo/DemoApplication.java
 create mode 100644 src/main/resources/application.properties
 create mode 100644 src/test/java/com/example/demo/DemoApplicationTests.java
[root@jenkins-master devops-maven-service-master]# git push -u origin master
Username for 'http://139.198.170.122:81': root
Password for 'http://root@139.198.170.122:81': 
Counting objects: 27, done.
Compressing objects: 100% (17/17), done.
Writing objects: 100% (27/27), 53.44 KiB | 0 bytes/s, done.
Total 27 (delta 0), reused 0 (delta 0)
To http://139.198.170.122:81/root/devops-maven-service.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

The resource folder contains configuration files

 

 

Maven common commands

  • mvn clean # clean up the build directory
  • mvn clean # package (there will be a unit test process here)
  • mvn clean install package deployment
  • mvn clean test unit test
  • mvn clean package -f ../pom.xml - f specifies the POM location\
  • mvn clean package -DskipTests / -Dmaven.test.skip=true skip single test
  • mvn deploy publish package to artifact Library

Many dependencies will be downloaded when packaging. Alibaba cloud maven source https://developer.aliyun.com/article/597934 

The following is the modified plug-in source

[root@jenkins-master ~]# vim /usr/local/apache-maven-3.8.1/conf/settings.xml

<mirror>
      <id>alimaven</id>
      <mirrorOf>central</mirrorOf>  
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>      
    </mirror>

The packages downloaded by maven will be cached in the directory

  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->


[root@jenkins-master repository]# ls
aopalliance  backport-util-concurrent  classworlds  commons-codec  commons-logging  jakarta  junit  org
asm          ch                        com          commons-io     io               javax    net

There is an additional target directory here. The key is the application package demo-0.0.1-snapshot jar

[INFO] Replacing main artifact with repackaged archive
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  01:23 min
[INFO] Finished at: 2021-06-01T15:43:54+08:00
[INFO] ------------------------------------------------------------------------
[root@jenkins-master devops-maven-service-master]# ls target/
classes                  demo-0.0.1-SNAPSHOT.jar.original  generated-test-sources  maven-status      test-classes
demo-0.0.1-SNAPSHOT.jar  generated-sources                 maven-archiver          surefire-reports

This package can be started directly

[root@jenkins-master target]# java -jar demo-0.0.1-SNAPSHOT.jar 

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.4)

2021-06-01 15:49:32.004  INFO 26266 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT using Java 1.8.0_282 on jenkins-master with PID 26266 (/root/devops-maven-service-master/target/demo-0.0.1-SNAPSHOT.jar started by root in /root/devops-maven-service-master/target)
2021-06-01 15:49:32.014  INFO 26266 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2021-06-01 15:49:34.612  INFO 26266 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-06-01 15:49:34.651  INFO 26266 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-06-01 15:49:34.651  INFO 26266 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.44]
2021-06-01 15:49:34.773  INFO 26266 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-06-01 15:49:34.774  INFO 26266 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2615 ms
2021-06-01 15:49:35.960  INFO 26266 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-06-01 15:49:36.592  INFO 26266 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-06-01 15:49:36.658  INFO 26266 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 5.735 seconds (JVM running for 6.659)
2021-06-01 15:49:36.794  INFO 26266 --- [nio-8080-exec-1] o.apache.tomcat.util.http.parser.Cookie  : A cookie header was received [:sess=O8wndXnEhbZ6q3QOLzGcahd__76DVKul; kubesphere:sess.sig=Ne-55wTGJElmSDxUeGWe9KTXYlI; known_sign_in=Q3gvQ3FQL1l3ZEsxY0gxMXhLUEZmRWFOVmxJVVFKeE9TaDZvSkcyMWJiYkVnZ2JSQjN3UllCSTRjbTZSeG5jTmx3cC81ZXNtQnhiRTlrRmdwTXY3R3p4dFpqRVZjSTNlRUdNenFqMmw4UzRGNW5JMFRMWStYam1aL0dta05WWC8tLTNkeEdmNDNHdk5FYXl6TWlVc2kyS3c9PQ%3D%3D--04f1ffe0e68036b23c7888b13160cb5abaf925d4; _gitlab_session=25974412b939b115dbef9f436ff07db0] that contained an invalid cookie. That cookie will be ignored.
 Note: further occurrences of this error will be logged at DEBUG level.
2021-06-01 15:49:36.817  INFO 26266 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-06-01 15:49:36.818  INFO 26266 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-06-01 15:49:36.819  INFO 26266 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms

 

 

Pipeline pipeline construction

 

def buildTools = ["maven": "/usr/local/apache-maven-3.8.1"]

pipeline{
   
   agent {label "build"}

   stages{
     
     stage("GetCode"){
        steps{
            script{
                println("Download branch code----->${env.branchName}")
                checkout([$class: 'GitSCM', branches: [[name: "${env.branchName}"]], extensions: [], userRemoteConfigs: [[credentialsId: '823b86fe-2c1b-466e-b0c3-66ae6991449d', url: "${gitHttpURL}"]]])
            }
        }
     }

     stage("Build"){
         steps{
             script{
                sh "${buildTools["maven"]}/bin/mvn clean package"
             }
         }
     }

   }

}

 

Unit test

maven is sometimes not found here. Use the absolute path as follows

def buildTools = ["maven": "/usr/local/apache-maven-3.8.1"]

pipeline{
   
   agent {label "build"}

   stages{
     
     stage("GetCode"){
        steps{
            script{
                println("Download branch code----->${env.branchName}")
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: '823b86fe-2c1b-466e-b0c3-66ae6991449d', url: "${gitHttpURL}"]]])
            }
        }
     }

     stage("Build"){
         steps{
             script{
                sh "${buildTools["maven"]}/bin/mvn clean package"
             }
         }
     }

     stage("UnitTest"){
         steps{
             script{
               sh "${buildTools["maven"]}/bin/mvn test"
             }
         }
     }

   }

}

The unit test has a report of the plug-in junit. The following is the directory of the test report

[root@jenkins-master devops-maven-service-master]# ls target/surefire-reports/
com.example.demo.DemoApplicationTests.txt  TEST-com.example.demo.DemoApplicationTests.xml

The following path is relative to workspace

If the unit test fails, it will not be collected, so you need to add a post here

def buildTools = ["maven": "/usr/local/apache-maven-3.8.1"]

pipeline{
   
   agent {label "build"}

   stages{
     
     stage("GetCode"){
        steps{
            script{
                println("Download branch code----->${env.branchName}")
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: '823b86fe-2c1b-466e-b0c3-66ae6991449d', url: "${gitHttpURL}"]]])
            }
        }
     }

     stage("Build"){
         steps{
             script{
                sh "${buildTools["maven"]}/bin/mvn clean package"
             }
         }
     }

     stage("UnitTest"){
         steps{
             script{
               sh "${buildTools["maven"]}/bin/mvn test"
             }
         }
         post{
             success{
                script{
                     junit 'target/surefire-reports/*.xml'
                }
             }
         }
     }
  }

}

 

Added by lovelf on Tue, 01 Feb 2022 06:52:38 +0200