linuxea:jenkins流水线集成sonar分支扫描/关联gitlab/docker和mvn打包配置二(8)

marksugar
2022-07-07 / 0 评论 / 392 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年07月07日,已超过89天没有更新,若内容或图片失效,请留言反馈。

在前面的jenkins流水线集成juit/sonarqube/覆盖率扫描配置一中介绍了juilt,覆盖率以及soanrqube的一些配置实现。接着上一篇中,我们继续。

阅读此篇,你将了解如下列表中简单的实现方式:

  • jenkins和gitlab触发(上一章已实现)
  • jenkins凭据使用(上一章已实现)
  • juit配置(上一章已实现)
  • sonarqube简单扫描(上一章已实现)
  • sonarqube覆盖率(上一章已实现)
  • 打包基于java的skywalking agent(上一章已实现)
  • sonarqube与gitlab关联 (本章实现)
  • 配置docker中构建docker (本章实现)
  • mvn打包 (本章实现)
  • sonarqube简单分支扫描(本章实现)
  • 基于gitlab来管理kustomize的k8s配置清单
  • kubectl部署
  • kubeclt deployment的状态跟踪
  • 钉钉消息的构建状态推送

4.6 分支扫描

我们可能更希望扫描某一个分支,于是我们需要sonarqube-community-branch-plugin插件

我们在https://github.com/mc1arke/sonarqube-community-branch-plugin/releases中,留意支持的版本

Note: This version supports Sonarqube 8.9 and above. Sonarqube 8.8 and below or 9.0 and above are not supported in this release

使用下表查找每个 SonarQube 版本的正确插件版本

SonarQube 版本插件版本
9.1+1.12.0
9.01.9.0
8.91.8.2
8.7 - 8.81.7.0
8.5 - 8.61.6.0
8.2 - 8.41.5.0
8.11.4.0
7.8 - 8.01.3.2
7.4 - 7.71.0.2

于是,我们在nexus3上下载1.8.1版本

https://github.com/mc1arke/sonarqube-community-branch-plugin/releases/download/1.8.0/sonarqube-community-branch-plugin-1.8.0.jar
或者
https://github.91chifun.workers.dev//https://github.com/mc1arke/sonarqube-community-branch-plugin/releases/download/1.8.0/sonarqube-community-branch-plugin-1.8.0.jar

根据安装提示https://github.com/mc1arke/sonarqube-community-branch-plugin#manual-install

而后直接将 jar包下载在/data/sonarqube/extensions/plugins/下即可

wget http://172.16.100.48/jenkins/sonar-plugins/sonarqube-community-branch-plugin-1.8.0.jar -o /data/sonarqube/extensions/plugins/sonarqube-community-branch-plugin-1.8.0.jar
  • 实际上/data/sonarqube/extensions/目录被挂载到nexus的容器内的/opt/sonarqube/extensions下

而容器内的位置是不变的,因此挂载映射关系如下:

 volumes:
      - /etc/localtime:/etc/localtime
      - /data/sonarqube/conf:/opt/sonarqube/conf
      - /data/sonarqube/extensions:/opt/sonarqube/extensions
      - /data/sonarqube/logs:/opt/sonarqube/logs
      - /data/sonarqube/data:/opt/sonarqube/data
[root@linuxea-47 /data/sonarqube/extensions]# ll plugins/
total 17552
-rwx------ 1 1000 1000 10280677 Oct 10  2021 sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
-rwx------ 1 1000 1000    61903 Sep 11  2021 sonar-l10n-zh-plugin-8.9.jar
-rwx------ 1 1000 1000  7623167 Oct 10  2021 sonarqube-community-branch-plugin-1.8.0.jar

而后,我们在本地是/data/sonarqube/conf下的创建一个配置文件sonar.properties,内容如下

sonar.web.javaAdditionalOpts=-javaagent:./extensions/plugins/sonarqube-community-branch-plugin-1.8.0.jar=web
sonar.ce.javaAdditionalOpts=-javaagent:./extensions/plugins/sonarqube-community-branch-plugin-1.8.0.jar=ce

这个配置文件被映射到容器内的/opt/sonarqube/conf

进入容器查看

[root@linuxea-47 /data/sonarqube]# ls extensions/plugins/ -ll
total 17552
-rwx------ 1 1000 1000    61903 Sep 11  2021 sonar-l10n-zh-plugin-8.9.jar
-rwx------ 1 1000 1000  7623167 Oct 10  2021 sonarqube-community-branch-plugin-1.8.0.jar

分支扫描参数增加 –Dsonar.branch.name=

-Dsonar.branch.name=master

那现在的projetctkey就不需要加分支名字了

                        -Dsonar.projectKey=${JOB_NAME}_${branch} \
                        -Dsonar.projectName=${JOB_NAME}_${branch} \

直接在一个项目中就可以看到多个分支的扫描结果了

        stage("coed sonar"){
            steps{
              script {
                      withCredentials([string(credentialsId: 'sonarqube-token', variable: 'SONAR_TOKEN')]) {           
                          sh """
                              cd linuxea && \
                              /usr/local/package/sonar-scanner-4.6.2.2472-linux/bin/sonar-scanner \
                              -Dsonar.host.url=http://172.16.100.47:9000 \
                              -Dsonar.projectKey=${JOB_NAME} \
                              -Dsonar.projectName=${JOB_NAME} \
                              -Dsonar.projectVersion=${BUILD_NUMBER} \
                              -Dsonar.login=${SONAR_TOKEN} \
                              -Dsonar.ws.timeout=30 \
                              -Dsonar.projectDescription="my first project!" \
                              -Dsonar.links.homepage=${env.BASEURL} \
                              -Dsonar.links.ci=${BUILD_URL} \
                              -Dsonar.sources=src \
                              -Dsonar.sourceEncoding=UTF-8 \
                              -Dsonar.java.binaries=target/classes \
                              -Dsonar.java.test.binaries=target/test-classes \
                              -Dsonar.java.surefire.report=target/surefire-reports \
                              -Dsonar.core.codeCoveragePlugin=jacoco \
                              -Dsonar.jacoco.reportPaths=target/jacoco.exec \
                              -Dsonar.branch.name=${branch}
                          """
                  }
              }
            }
        }

此时我们分别构建master和web后,在sonarqube的UI中就会有两个分支的扫描结果

image-20220704220804210.png

  • 注意事项

如果你使用的是不同的版本,而不同的版本配置是不一样的。见github的每个分支,比如:1.5.0

4.7 关联gitlab

https://github.com/gabrie-allaigre/sonar-gitlab-plugin下载插件,参阅用法中版本对应,我们下载4.1.0

https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar

而后仍然存放到sonarqube的plugin目录下

[root@linuxea-47 ~]# ls /data/sonarqube/extensions/plugins/ -ll
total 17552
-rwx------ 1 1000 1000 10280677 Oct 10  2021 sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
-rwx------ 1 1000 1000    61903 Sep 11  2021 sonar-l10n-zh-plugin-8.9.jar
-rwx------ 1 1000 1000  7623167 Oct 10  2021 sonarqube-community-branch-plugin-1.8.0.jar

这在启动的时候,实际上可以看到日志加载

image-20220705195528768.png

根据文档,要完成扫描必须提供如下必要参数

-Dsonar.gitlab.commit_sha=1632c729e8f78f913cbf0925baa2a8c893e4473b \ 版本sha
-Dsonar.gitlab.ref_name=master \  分支
-Dsonar.gitlab.project_id=16 \  项目id
-Dsonar.dynamicAnalysis=reuseReports \  扫描方式
-Dsonar.gitlab.failure_notification_mode=commit-status \  更改提交状态
-Dsonar.gitlab.url=http://192.168.1.200 \  gitlab地址
-Dsonar.gitlab.user_token=k8xLe6dYTzdtoewSysmy \  gitlab token
-Dsonar.gitlab.api_version=v4

1.配置一个全局token

至少需要如下权限

image-20220705195656753.png

令牌如下

K8DtxxxifxU1gQeDgvDK

其他信息根据现有的项目输入即可

image-20220705200013476.png

-Dsonar.gitlab.commit_sha=4a5bb3db1c845cddc86290d137ef694b3b076d0e \ 版本sha
-Dsonar.gitlab.ref_name=master \  分支
-Dsonar.gitlab.project_id=19 \  项目id
-Dsonar.dynamicAnalysis=reuseReports \  扫描方式
-Dsonar.gitlab.failure_notification_mode=commit-status \  更改提交状态
-Dsonar.gitlab.url=http://172.16.100.47 \  gitlab地址
-Dsonar.gitlab.user_token=K8DtxxxifxU1gQeDgvDK \  gitlab token
-Dsonar.gitlab.api_version=v4

2.将上述命令添加到sonarqube的流水线中

/var/jenkins_home/package/sonar-scanner/bin/sonar-scanner \
-Dsonar.host.url=http://172.16.15.136:9000 \
-Dsonar.projectKey=java-demo \
-Dsonar.projectName=java-demo \
-Dsonar.projectVersion=120 \
-Dsonar.login=636558affea60cc5f264247de36e7c27c817530b \
-Dsonar.ws.timeout=30 \
-Dsonar.projectDescription="my first project!" \
-Dsonar.links.homepage=http://172.16.15.136:180/devops/java-demo.git \
-Dsonar.links.ci=http://172.16.15.136:8088/job/java-demo/120/ \
-Dsonar.sources=src \
-Dsonar.sourceEncoding=UTF-8 \
-Dsonar.java.binaries=target/classes -Dsonar.java.test.binaries=target/test-classes \
-Dsonar.java.surefire.report=target/surefire-reports \
-Dsonar.branch.name=main \
-Dsonar.gitlab.commit_sha=9353e89a7b42e0d93ddf95520408ecfde9a5144a \
-Dsonar.gitlab.ref_name=main \
-Dsonar.gitlab.project_id=2 \
-Dsonar.dynamicAnalysis=reuseReports \
-Dsonar.gitlab.failure_notification_mode=commit-status \
-Dsonar.gitlab.url=http://172.16.15.136:180 \
-Dsonar.gitlab.user_token=9mszu2KXx7nHXiwJveBs \
-Dsonar.gitlab.api_version=v4

运行测试

image-20220705171217192.png

image-20220705171441861.png

正常是什么样的呢,换一个环境配置下

/usr/local/package/sonar-scanner-4.6.2.2472-linux/bin/sonar-scanner \
                            -Dsonar.host.url=http://172.16.100.47:9000 \
                            -Dsonar.projectKey=java-demo \
                            -Dsonar.projectName=java-demo \
                            -Dsonar.projectVersion=20 \
                            -Dsonar.login=bc826f124d691127c351388274667d7deb1cc9b2 \
                            -Dsonar.ws.timeout=30 \
                            -Dsonar.projectDescription="my first project!" \
                            -Dsonar.links.homepage=www.baidu.com \
                            -Dsonar.links.ci=20 \
                            -Dsonar.sources=src \
                            -Dsonar.sourceEncoding=UTF-8 \
                            -Dsonar.java.binaries=target/classes \
                            -Dsonar.java.test.binaries=target/test-classes \
                            -Dsonar.java.surefire.report=target/surefire-reports \
                            -Dsonar.core.codeCoveragePlugin=jacoco \
                            -Dsonar.jacoco.reportPaths=target/jacoco.exec \
                            -Dsonar.branch.name=master \
                            -Dsonar.gitlab.commit_sha=4a5bb3db1c845cddc86290d137ef694b3b076d0e \
                            -Dsonar.gitlab.ref_name=master \
                            -Dsonar.gitlab.project_id=19 \
                            -Dsonar.dynamicAnalysis=reuseReports \
                            -Dsonar.gitlab.failure_notification_mode=commit-status \
                            -Dsonar.gitlab.url=http://172.16.100.47 \
                            -Dsonar.gitlab.user_token=K8DtxxxifxU1gQeDgvDK \
                            -Dsonar.gitlab.api_version=v4  

执行之后

INFO: SCM Publisher SCM provider for this project is: git
INFO: SCM Publisher 2 source files to be analyzed
INFO: SCM Publisher 2/2 source files have been analyzed (done) | time=704ms
INFO: CPD Executor 2 files had no CPD blocks
INFO: CPD Executor Calculating CPD for 0 files
INFO: CPD Executor CPD calculation finished (done) | time=0ms
INFO: Analysis report generated in 42ms, dir size=74 KB
INFO: Analysis report compressed in 14ms, zip size=13 KB
INFO: Analysis report uploaded in 468ms
INFO: ANALYSIS SUCCESSFUL, you can browse http://172.16.100.47:9000/dashboard?id=java-demo&branch=master
INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
INFO: More about the report processing at http://172.16.100.47:9000/api/ce/task?id=AYHOP018DZyaRsN1subY
INFO: Executing post-job 'GitLab Commit Issue Publisher'
INFO: Waiting quality gate to complete...
INFO: Quality gate status: OK
INFO: Duplicated Lines : 0
INFO: Lines of Code : 18
INFO: Report status=success, desc=SonarQube reported QualityGate is ok, with 2 ok, no issues
INFO: Analysis total time: 7.130 s
INFO: ------------------------------------------------------------------------
INFO: EXECUTION SUCCESS
INFO: ------------------------------------------------------------------------
INFO: Total time: 7.949s
INFO: Final Memory: 17M/60M
INFO: ------------------------------------------------------------------------

image-20220705200633433.png

流水线已通过
image-20220705200655588.png

3.获取参数

现在的问题是,手动输入gitlab的这些值不可能在jenkins中输入,我们需要自动获取这些。

  • 分支的环境变量通过传递来,用变量获取即可
  • commit_sha通过读取当前代码中的文件实现
  • gitlab token放到密钥管理当中

于是,我们通过jq来获取格式化gitlab api返回值获取缺省的项目id

需要下载一个jq程序在jenkins节点上。于是我们在https://stedolan.github.io/jq/download/页面下载一个 binaries二进制的即可

https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64

获取项目id

 curl --silent --header "PRIVATE-TOKEN: K8DtxxxifxU1gQeDgvDK"     "http://gitlab.marksugar.com/api/v4/projects?simple=true"| jq -rc '.[]|select(.name == "java-demo")'|jq .id

示例1:

如果项目名称在所有组内是唯一的,就可以使用jq -rc '.[]|select(.name == "java-demo")',如下

  • .name == "java-demo": 项目名
curl --silent --header "PRIVATE-TOKEN: K8DtxxxifxU1gQeDgvDK"     "http://gitlab.marksugar.com/api/v4/projects?simple=true"| jq -rc '.[]|select(.name == "java-demo")' | jq .id

示例2:

如果项目名称在所有组内不是唯一,且有多个的,用jq -rc '.[]|select(.path_with_namespace == "java/java-demo")',如下

  • .path_with_namespace == java/java-demo : 组名/项目名
curl --silent --header "PRIVATE-TOKEN: K8DtxxxifxU1gQeDgvDK"     "http://gitlab.marksugar.com/api/v4/projects?simple=true"| jq -rc  '.[]|select(.path_with_namespace == "java/java-demo")'|jq .id

获取当前的sha版本号

获取办版本号只需要在当前项目目录内读取文件或者命令即可,it log --pretty=oneline|head -1| cut -b 1-40,如下

[root@linuxea-48 /data/jenkins-latest/jenkins_home/workspace/linuxea-2022]# git log --pretty=oneline|head -1| cut -b 1-40
4a5bb3db1c845cddc86290d137ef694b3b076d0e

除此之外使用cut -b -40 .git/refs/remotes/origin/master 能获得一样的效果

[root@linuxea-48 /data/jenkins-latest/jenkins_home/workspace/linuxea-2022]# cut -b -40 .git/refs/remotes/origin/master 
4a5bb3db1c845cddc86290d137ef694b3b076d0e

项目名称

项目名称,我们可以使用Jenkins的项目名字。但是,这个名字有时候未必和git的项目名称一样,于是,我们直接截取项目的地址名称

JOB_NAMES=sh (script: """echo ${BASEURL.split("/")[-1]} | cut -d . -f 1""",returnStdout: true).trim()    

那么现在已经具备上面的几个关键参数,现在分别命名GIT_COMMIT_TAGSHAProjects_GitId,JOB_NAMES

environment {
    def GIT_COMMIT_TAGSHA=sh (script: """cut -b -40 .git/refs/remotes/origin/master""",returnStdout: true).trim()
    def JOB_NAMES=sh (script: """echo ${BASEURL.split("/")[-1]} | cut -d . -f 1""",returnStdout: true).trim()          
    def Projects_GitId=sh (script: """curl --silent --header "PRIVATE-TOKEN: zrv1vpfZTtEFCJGrJczB"  "http://gitlab.marksugar.com/api/v4/projects?simple=true"| ${buildMap["jq"]} -rc '.[]|select(.path_with_namespace == "java/java-demo")'| ${buildMap["jq"]} .id""",returnStdout: true).trim()
}

那么现在的环境变量就是

    environment {
        def tag_time = new Date().format("yyyyMMddHHmm")        
        def IPATH="harbor.marksugar.com/java/${JOB_NAME}:${tag_time}"    
        def GIT_COMMIT_TAGSHA=sh (script: """cut -b -40 .git/refs/remotes/origin/master""",returnStdout: true).trim()
        def JOB_NAMES=sh (script: """echo ${BASEURL.split("/")[-1]} | cut -d . -f 1""",returnStdout: true).trim()          
        def Projects_GitId=sh (script: """curl --silent --header "PRIVATE-TOKEN: zrv1vpfZTtEFCJGrJczB"  "http://gitlab.marksugar.com/api/v4/projects?simple=true"| ${buildMap["jq"]} -rc '.[]|select(.path_with_namespace == "java/java-demo")'| ${buildMap["jq"]} .id""",returnStdout: true).trim()
        def SONAR_git_TOKEN="K8DtxxxifxU1gQeDgvDK"
        def GitLab_Address="http://172.16.100.47"
    } 

而新增的调用的命令如下

                            -Dsonar.gitlab.commit_sha=${GIT_COMMIT_TAGSHA} \
                            -Dsonar.gitlab.ref_name=${branch} \
                            -Dsonar.gitlab.project_id=${Projects_GitId} \
                            -Dsonar.dynamicAnalysis=reuseReports \
                            -Dsonar.gitlab.failure_notification_mode=commit-status \
                            -Dsonar.gitlab.url=${GitLab_Address} \
                            -Dsonar.gitlab.user_token=${SONAR_git_TOKEN} \
                            -Dsonar.gitlab.api_version=v4   

构建一次
image-20220705204441477.png

能够看到已经获取到的值,构建成功的

完整的阶段代码如下:

        stage("coed sonar"){
            environment {    
                def GIT_COMMIT_TAGSHA=sh (script: """cut -b -40 .git/refs/remotes/origin/master""",returnStdout: true).trim()
                def JOB_NAMES=sh (script: """echo ${BASEURL.split("/")[-1]} | cut -d . -f 1""",returnStdout: true).trim()          
                def Projects_GitId=sh (script: """curl --silent --heade "PRIVATE-TOKEN: zrv1vpfZTtEFCJGrJczB"  "http://gitlab.marksugar.com/api/v4/projects?simple=true"| /usr/local/package/jq-1.6/jq -rc '.[]|select(.path_with_namespace == "java/java-demo")'| /usr/local/package/jq-1.6/jq .id""",returnStdout: true).trim()
                def SONAR_git_TOKEN="K8DtxxxifxU1gQeDgvDK"
                def GitLab_Address="http://172.16.100.47"
            }            
            steps{           
              script {
                      withCredentials([string(credentialsId: 'sonarqube-token', variable: 'SONAR_TOKEN')]) {           
                          sh """
                            cd linuxea && \
                            /usr/local/package/sonar-scanner-4.6.2.2472-linux/bin/sonar-scanner \
                            -Dsonar.host.url=${GitLab_Address}:9000 \
                            -Dsonar.projectKey=${JOB_NAME} \
                            -Dsonar.projectName=${JOB_NAME} \
                            -Dsonar.projectVersion=${BUILD_NUMBER} \
                            -Dsonar.login=${SONAR_TOKEN} \
                            -Dsonar.ws.timeout=30 \
                            -Dsonar.projectDescription="my first project!" \
                            -Dsonar.links.homepage=${env.BASEURL} \
                            -Dsonar.links.ci=${BUILD_URL} \
                            -Dsonar.sources=src \
                            -Dsonar.sourceEncoding=UTF-8 \
                            -Dsonar.java.binaries=target/classes \
                            -Dsonar.java.test.binaries=target/test-classes \
                            -Dsonar.java.surefire.report=target/surefire-reports \
                            -Dsonar.core.codeCoveragePlugin=jacoco \
                            -Dsonar.jacoco.reportPaths=target/jacoco.exec \
                            -Dsonar.branch.name=${branch} \
                            -Dsonar.gitlab.commit_sha=${GIT_COMMIT_TAGSHA} \
                            -Dsonar.gitlab.ref_name=${branch} \
                            -Dsonar.gitlab.project_id=${Projects_GitId} \
                            -Dsonar.dynamicAnalysis=reuseReports \
                            -Dsonar.gitlab.failure_notification_mode=commit-status \
                            -Dsonar.gitlab.url=${GitLab_Address} \
                            -Dsonar.gitlab.user_token=${SONAR_git_TOKEN} \
                            -Dsonar.gitlab.api_version=v4
                          """
                  }
              }
            }
        }

4.8 mvn 打包

我们是哟个一条命令直接进行打包

  • -Dmaven.test.skip=true,不执行测试用例,也不编译测试用例类
  • -Dmaven.test.failure.ignore=true ,忽略单元测试失败
  • -s ~/.m2/settings.xml,指定mvn构建的配置文件位置
mvn clean install -Dautoconfig.skip=true -Dmaven.test.skip=false -Dmaven.test.failure.ignore=true -s /var/jenkins_home/.m2/settings.xml

阶段如下

          stage("mvn build"){
            steps {
                script {
                    sh """
                    cd linuxea
                    mvn clean install -Dautoconfig.skip=true -Dmaven.test.skip=false -Dmaven.test.failure.ignore=true -s /var/jenkins_home/.m2/settings.xml
                    """
                    }
            }
        }

4.9 推送镜像

我们先需要将docker配置好,首先容器内需要安装docker,而后挂载socket

如果你的系统是和容器系统的库文件一样,你可以将本地的docker二进制文件挂载到容器内,但是我使用的是alpine,因此我在容器内安装了docker,此时只需要挂载目录和sock即可

也可以将docker挂载到容器内即可

      - /usr/bin/docker:/usr/bin/docker
      - /etc/docker:/etc/docker
      - /var/run/docker.sock:/var/run/docker.sock

并在容器内登录docker

容器内登录,或者在流水线阶段中登录也可以

[root@linuxea-48 /data/jenkins-latest/jenkins_home]# docker exec -it jenkins bash
bash-5.1# cat ~/.docker/config.json 
{
    "auths": {
        "harbor.marksugar.com": {
            "auth": "YWRtaW46SGFyYm9yMTIzNDU="
        }
    }
}

将配置复制到主机并挂载到容器内,或者在主机登录挂载到容器都可以

- /data/jenkins-latest/.docker:/root/.docker

能够在容器内查看docker命令

bash-5.1# docker ps -a
CONTAINER ID   IMAGE                                                                                                 COMMAND                  CREATED             STATUS             PORTS     NAMES
536cb1dbeb3f   registry.cn-hangzhou.aliyuncs.com/marksugar/jenkins:2.332-3-alpine-ansible-maven3-nodev16.15-latest   "/sbin/tini -- /usr/…"   About an hour ago   Up About an hour             jenkins

而后配置docker推送阶段

开始之前要配置环境变量,用于获取镜像的时间

  • tag_time随机时间
    agent any
    environment {
        def tag_time = new Date().format("yyyyMMddHHmm")        
        def IPATH="harbor.marksugar.com/java/${JOB_NAME}:${tag_time}"    
    }

docker阶段

请注意:此时在COPY skywalking-agent的时候,需要将包拷贝到当前目录才能COPY到容器内

        stage("docker build"){
            steps{
                script{
                   sh """
                        cd linuxea
                        docker ps -a
                        cp -r /usr/local/package/skywalking-agent ./
                        docker build -f ./Dockerfile -t $IPATH .
                        docker push $IPATH
                        docker rmi -f $IPATH
                   """
                }
            }
        }

与此同时需要修改Dockerfile中的COPY 目录

而后创建harbor仓库
image-20220703230758733.png

开始构建

image-20220703231033601.png

一旦构建完成,镜像将会推送到harbor仓库

image-20220703231126919.png

此时的pipeline流水线i清单如下

try {
    if ( "${onerun}" == "gitlabs"){
        println("Trigger Branch: ${info_ref}")
        RefName="${info_ref.split("/")[-1]}"
        //自定义显示名称
        currentBuild.displayName = "#${info_event_name}-${RefName}-${info_checkout_sha}"
        //自定义描述
        currentBuild.description = "Trigger by user ${info_user_username} 自动触发 \n branch: ${RefName} \n commit message: ${info_commits_0_message}"
        BUILD_TRIGGER_BY="${info_user_username}"
        BASEURL="${info_project_git_http_url}"
    } 
}catch(e){
    BUILD_TRIGGER_BY="${currentBuild.getBuildCauses()[0].userId}"
    currentBuild.description = "Trigger by user ${BUILD_TRIGGER_BY} 非自动触发 \n branch: ${branch} \ngit: ${BASEURL}"
}
pipeline{
    //指定运行此流水线的节点
    agent any
    environment {
        def tag_time = new Date().format("yyyyMMddHHmm")        
        def IPATH="harbor.marksugar.com/java/${JOB_NAME}:${tag_time}"    
    }    
    //管道运行选项
    options {
        skipDefaultCheckout true
        skipStagesAfterUnstable()
        buildDiscarder(logRotator(numToKeepStr: '2'))
    }
    //流水线的阶段
    stages{
        //阶段1 获取代码
          stage("CheckOut"){
            steps {
                script {
                    println("下载代码 --> 分支: ${env.branch}")
                    checkout(   [$class: 'GitSCM', 
                        branches: [[name: "${branch}"]], 
                        extensions: [], 
                        userRemoteConfigs: [[
                            credentialsId: 'gitlab-mark', 
                            url: "${BASEURL}"]]])
                    }
            }
        }
        stage("unit Test"){
            steps{
                script{
                sh """
                        cd linuxea && mvn test -s /var/jenkins_home/.m2/settings.xml2
                """
                }
            }
            post {
                success {
                    script {
                    junit 'linuxea/target/surefire-reports/*.xml'
                    }
                }
            }
        }
        stage("coed sonar"){
            environment {    
                def GIT_COMMIT_TAGSHA=sh (script: """cut -b -40 .git/refs/remotes/origin/master""",returnStdout: true).trim()
                def JOB_NAMES=sh (script: """echo ${BASEURL.split("/")[-1]} | cut -d . -f 1""",returnStdout: true).trim()          
                def Projects_GitId=sh (script: """curl --silent --heade "PRIVATE-TOKEN: zrv1vpfZTtEFCJGrJczB"  "http://gitlab.marksugar.com/api/v4/projects?simple=true"| /usr/local/package/jq-1.6/jq -rc '.[]|select(.path_with_namespace == "java/java-demo")'| /usr/local/package/jq-1.6/jq .id""",returnStdout: true).trim()
                def SONAR_git_TOKEN="K8DtxxxifxU1gQeDgvDK"
                def GitLab_Address="http://172.16.100.47"
            }            
            steps{           
              script {
                      withCredentials([string(credentialsId: 'sonarqube-token', variable: 'SONAR_TOKEN')]) {           
                          sh """
                            cd linuxea && \
                            /usr/local/package/sonar-scanner-4.6.2.2472-linux/bin/sonar-scanner \
                            -Dsonar.host.url=${GitLab_Address}:9000 \
                            -Dsonar.projectKey=${JOB_NAME} \
                            -Dsonar.projectName=${JOB_NAME} \
                            -Dsonar.projectVersion=${BUILD_NUMBER} \
                            -Dsonar.login=${SONAR_TOKEN} \
                            -Dsonar.ws.timeout=30 \
                            -Dsonar.projectDescription="my first project!" \
                            -Dsonar.links.homepage=${env.BASEURL} \
                            -Dsonar.links.ci=${BUILD_URL} \
                            -Dsonar.sources=src \
                            -Dsonar.sourceEncoding=UTF-8 \
                            -Dsonar.java.binaries=target/classes \
                            -Dsonar.java.test.binaries=target/test-classes \
                            -Dsonar.java.surefire.report=target/surefire-reports \
                            -Dsonar.core.codeCoveragePlugin=jacoco \
                            -Dsonar.jacoco.reportPaths=target/jacoco.exec \
                            -Dsonar.branch.name=${branch} \
                            -Dsonar.gitlab.commit_sha=${GIT_COMMIT_TAGSHA} \
                            -Dsonar.gitlab.ref_name=${branch} \
                            -Dsonar.gitlab.project_id=${Projects_GitId} \
                            -Dsonar.dynamicAnalysis=reuseReports \
                            -Dsonar.gitlab.failure_notification_mode=commit-status \
                            -Dsonar.gitlab.url=${GitLab_Address} \
                            -Dsonar.gitlab.user_token=${SONAR_git_TOKEN} \
                            -Dsonar.gitlab.api_version=v4
                          """
                  }
              }
            }
        }
          stage("mvn build"){
            steps {
                script {
                    sh """
                    cd linuxea
                    mvn clean install -Dautoconfig.skip=true -Dmaven.test.skip=false -Dmaven.test.failure.ignore=true -s /var/jenkins_home/.m2/settings.xml2
                    """
                    }
            }
        }
        stage("docker build"){
            steps{
                script{
                   sh """
                        cd linuxea
                        docker ps -a
                        cp -r /usr/local/package/skywalking-agent ./
                        docker build -f ./Dockerfile -t $IPATH .
                        docker push $IPATH
                        docker rmi -f $IPATH
                   """
                }
            }
        }
    }
}
0

评论

博主关闭了当前页面的评论