Groovy脚本:

#!groovy

@Library('jenkinslib@master') _

def tools = new org.devops.tools();


pipeline{
	agent{
		node{
			label "master"
		}
	}
	
	stages{
		stage("Checkout"){
			steps{
				script{
					tools.PrintMes("获取代码","green")
					
					checkout([
						$class: 'GitSCM', branches: [[name: '*/master']], 
						doGenerateSubmoduleConfigurations: false, extensions: [], 
						submoduleCfg: [], 
						userRemoteConfigs: [
							[
								credentialsId: '398170a9-72a6-410b-8293-334687f152da', 
								url: 'http://192.168.0.26/qiyang/solo.git'
							]
						]
					])
				
				}
			}
		}
		
		stage("build"){
			steps{
				script{
					tools.PrintMes("编译","green")
					
					mvnHome = tool "M2"
					sh "${mvnHome}/bin/mvn clean package -Dmaven.test.skip=true"
				}
			}
		}
		
		stage("NexusUpload"){
			steps{
				script{
					tools.PrintMes("NexusUpload","green")
					def jarName = sh returnStdout: true, script: "cd target;ls *.war"
					env.jarName = jarName - "\n"
					def pom = readMavenPom file: 'pom.xml' // 需要安装 pipeline-utility-steps 插件
					env.pomVersion = "${pom.version}" // 需要到 “Manage Jenkins” -> “In-process Script Approval”点击approval
					env.pomArtifact = "${pom.artifactId}"
					env.pomPackaging = "${pom.packaging}"
					env.pomGroupId = "${pom.groupId}"
					
					tools.PrintMes("--------------------","green")
					println("${env.jarName}-${pomGroupId}-${pomArtifact}-${pomVersion}-${pomPackaging}")
					
					def mvnHome = tool "M2"
					
					// 需要在 /usr/local/maven/conf/settings.xml 中加入Nexus的账号和密码
					sh """
					cd target/
					${mvnHome}/bin/mvn deploy:deploy-file -Dmaven.test.skip=true \
					-Dfile=${env.jarName} -DgroupId=${pomGroupId} \
					-DartifactId=${pomArtifact} -Dversion=${pomVersion} \
					-Dpackaging=${pomPackaging} -DrepositoryId=maven-releases \
					-Durl=http://192.168.0.26:8081/repository/maven-releases/
					"""
					
				}
			}
		}
		
		stage("test"){
			steps{
				echo "${createVersion(BUILD_NUMBER)}"
				hello("Hi!")
				//sh "printenv"
			}
		}
	}
	
}
def createVersion(String BUILD_NUMBER){
	return new Date().format('yymm')+"-${BUILD_NUMBER}"
}

注意点:

插件安装:读取pom文件信息需要安装一个插件,名称如下

pipeline-utility-steps

jenkins的配置:获取版本信息需要在jenkins中添加Approvals信息。

“Manage Jenkins” -> “In-process Script Approval”点击approval

image.png

image.png


maven的配置:在配置文件 /usr/local/maven/conf/settings.xml 中的servers标签中添加Nexus的账号和密码,用于maven上传制品到Nexus中。

  </servers>
    <server>
      <id>maven-releases</id>
      <username>admin</username>
      <password>qiyang</password>
    </server>
  </servers>