一、jenkins 配置Pipeline
二、新建共享库执行脚本
共享库可以是一个普通的gitlab项目,目录结构如下
三、添加到共享库
Jenkins Dashboard–>系统管理–>系统配置–>Global Pipeline Libraries
Name: 共享库名称,自定义即可;
Default version: 共享库版本,输入版本库分支名称、Tag 名称、Commit 值其中之一即可;
Load implicitly:如果选中,脚本将自动访问这个库,而不需要通过@Library请求它即隐式加载;
Allow default version to be overridden:如果选中,脚本可以通过在@Library注释中添加@someversion来选择库的自定义版本。否则,他们被限制使用您在这里选择的版本;
Include @Library changes in job recent changes:如果选中该选项,库中的任何更改都将包含在构建的更改集中,而更改库将导致为包含此库的管道运行新的构建。@Library(value=“name@version”, changelog=true|false),意思可以重写调用版本;
Cache fetched versions on controller for quick retrieval:如果选中此项,使用此库获取的版本将缓存在控制器上;
Retrieval method: 配置公共库获取的方式,并配置 Git 相关信息;
Library Path (optional):允许您设置从 SCM 根目录到库目录根目录的相对路径,可选参数;
四、如何引用共享库
在自定义的 Pipeline或者 Jenkinsfile 中通改过@Libray 形式进行引用,Jenkinsfile如下:
Jenkinsefile
@Library("mylib@main") _ def mytools = new org.devops.tools() def sonarapi = new org.devops.sonarapi() pipeline { agent { label "onemap-gch" } stages { stage('Pull Code') { steps { checkout([$class: 'GitSCM', branches: [[name: '*/dev']], extensions: [], userRemoteConfigs: [[credentialsId: 'b78b9ca3-a0ea-422b-b8d6-fa9dc030403a', url: 'http://192.168.2.16/develop/beautiful-village-java.git']]]) } } stage ('Sonar Scan') { steps { script { def sonarqubeScanner = tool 'sonarqube-scanner-4.8'; withSonarQubeEnv(credentialsId: 'sonar_token') { sh "${sonarqubeScanner}/bin/sonar-scanner " + "-Dsonar.projectName=beautiful-village " + "-Dsonar.projectKey=com.gj.map.village.beautiful-village " + "-Dsonar.projectVersion=1.0 " + "-Dsonar.sourceEncoding=utf8 " + "-Dsonar.sources=src/main/java " + "-Dsonar.language=java " + "-Dsonar.java.binaries=target/classes" } // (9) 暂停10s等待sonarqube扫描反馈 sh "sleep 10s" // 方式1 timeout(1) { def qg = waitForQualityGate() if (qg.status != 'OK') { error "未通过Sonarqube的代码质量阈检查,请及时修改!failure: ${qg.status}" } else { echo "successful" } } } } } stage('Maven Build') { steps { sh '/home/maven/apache-maven-3.8.5/bin/mvn clean package -DskipTests' } } stage('Publish Over SSH') { steps { sshPublisher(publishers: [sshPublisherDesc(configName: '241', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: 'cd /opt/workspace/beautiful-village && ./start.sh', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '/beautiful-village', remoteDirectorySDF: false, removePrefix: 'target/', sourceFiles: 'target/*.jar')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)]) } } } }