1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
def remotes = [
[name: "project-1", host: "IP", allowAnyHosts: true],
// 可以继续添加更多的 remote
]
pipeline {
agent any
environment {
// 用于配置后面的文件名
PROJECT = 'PROJECT_NAME'
}
stages {
stage('Preparation') {
steps {
// Git拉取代码
git branch: 'dev', credentialsId: '403F_VCS', url: 'https://git.url'
}
}
stage('Maven Package') {
steps {
script {
// 这里的maven-3.9.8是在系统配置中配置完成的
withMaven(globalMavenSettingsConfig: 'maven_mirror_and_properties', maven: 'maven-3.9.8', mavenSettingsConfig: '', traceability: true) {
// JAVA_HOME特别采用jdk_1.8是因为当前项目代码中用了javax,必须要用8
withEnv(["JAVA_HOME=/var/jenkins_home/tools/jdk_1.8"]) {
sh '"mvn" clean package -U'
}
}
}
}
}
// 这一阶段会获取Git Commit Hash并进行组合后形成新的文件名
stage('Post Process Artifacts') {
steps {
script {
echo "${PROJECT}"
// 获取Commit Hash以供后面使用
def commitHash = sh(script: 'git log -n 1 --pretty=format:\'%H\'', returnStdout: true).trim()
def project = "${PROJECT}"
def fileName = "${new Date().format('yyyyMMddHHmmss')}-${commitHash}.war"
echo "Build project ${project}, git commit ${commitHash}"
// 删除掉target文件夹中生成的其他文件,只留存一个最终的war包
sh "find target -mindepth 1 -type f ! -name '*.war' -exec rm -f {} +"
sh "find target -mindepth 1 -type d ! -name '.' ! -name '..' -exec rm -rf {} +"
def warFilesCount = sh(script: 'ls target/*.war 2>/dev/null | wc -l', returnStdout: true).trim().toInteger()
// 确保最终留下来的war包只有一个
if (warFilesCount == 1) {
def warFile = sh(script: 'ls target/*.war', returnStdout: true).trim()
if (fileName.isEmpty()) {
error "file_name env variable not found!"
}
// 重命名最终的war包
sh "mv '${warFile}' 'target/${project}_${fileName}'"
echo "WAR file renamed"
} else {
error "WAR file in target not single!"
}
}
}
}
// 留存一份最终的war包供后续归档与回滚等使用
stage('Results') {
steps {
archiveArtifacts artifacts: 'target/*.war'
}
}
// 部署阶段
stage('Deploy') {
steps {
script {
// 所有需要部署的服务器采用同一个SSH RSA Key,这样可以保证一个用户凭证可以连接所有的服务器
withCredentials([sshUserPrivateKey(credentialsId: 'aliyun-prod', keyFileVariable: 'identity', usernameVariable: 'username')]) {
remotes.each { remote ->
remote.user = userName
remote.identityFile = identity
stage("Stop Tomcat server") {
sshCommand remote:remote, command: 'bash /usr/local/deploy/shutdown.sh'
}
stage("Upload new WAR package") {
def warFile = sh(script: 'ls target/*.war 2>/dev/null', returnStdout: true).trim()
sshPut remote: remote, from: warFile, into: '/usr/local/deploy/server.war'
}
stage("Start up Tomcat") {
sshCommand remote:remote, command: 'bash /usr/local/deploy/start.sh'
}
stage("Check Tomcat startup status") {
sshCommand remote:remote, command: 'bash /usr/local/deploy/check.sh'
}
}
}
}
}
}
}
}
|