-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile
78 lines (56 loc) · 2.5 KB
/
Jenkinsfile
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
// env 是 jenkins 提供的环境变量
String buildNumber = env.BUILD_NUMBER;
String timestamp = new Date().format('yyyyMMddHHmmss');
String projectName = env.JOB_NAME.split(/\//)[0];
// e.g awesome-project/release/RELEASE-1.0.0
String branchName = env.JOB_NAME.split(/\//)[1..-1].join(/\//);
println("${buildNumber} ${timestamp} ${projectName}");
String version = "${buildNumber}-${timestamp}-${projectName}";
node {
checkout scm;
// 检查构建参数是回滚还是正常构建
if(params.BuildType=='Rollback') {
return rollback()
} else if(params.BuildType=='Normal'){
return normalCIBuild(version)
} else if(branchName == 'master'){ // 第一次构建时的初始设置
setScmPollStrategyAndBuildTypes(['Normal', 'Rollback']);
}
}
def normalCIBuild(String version) {
stage 'test & package'
sh('./mvnw clean package')
stage('docker build')
sh("docker build . -t 192.168.31.83:5000/blog-springboot:${version}")
sh("docker push 192.168.31.83:5000/blog-springboot:${version}")
stage('deploy')
input 'deploy?' // 询问用户是否确认进行部署
deployVersion(version)
}
def deployVersion(String version) {
sh "ssh root@192.168.31.83 'docker rm -f my-blog && docker run --name my-blog -d -p 8080:8080 192.168.31.83:5000/blog-springboot:${version}'"
}
// 设置源代码管理系统轮询策略和构建类型
def setScmPollStrategyAndBuildTypes(List buildTypes) {
def propertiesArray = [
parameters([choice(choices: buildTypes.join('\n'), description: '', name: 'BuildType')]),
pipelineTriggers([[$class: "SCMTrigger", scmpoll_spec: "* * * * *"]]) // cron 表达式,表示每分钟检查一次git仓库以进行构建
];
properties(propertiesArray);
}
def rollback() {
def dockerRegistryHost = "http://192.168.31.83:5000";
def getAllTagsUri = "/v2/blog-springboot/tags/list";
def responseJson = new URL("${dockerRegistryHost}${getAllTagsUri}")
.getText(requestProperties: ['Content-Type': "application/json"]);
println(responseJson)
// {name:xxx,tags:[tag1,tag2,...]}
Map response = new groovy.json.JsonSlurperClassic().parseText(responseJson) as Map;
def versionsStr = response.tags.join('\n');
def rollbackVersion = input(
message: 'Select a version to rollback',
ok: 'OK',
parameters: [choice(choices: versionsStr, description: 'version', name: 'version')])
println rollbackVersion
deployVersion(rollbackVersion)
}