chaoz的杂货铺

生命有息、学无止境、折腾不止

0%

jenkins进阶笔记

基本命令

catchError:异常处理

两种写法:
最终结果 jenkins 都会判断为成功。

1
2
3
4
5
6
7
8
9
10
11
node {
try {
sh 'might fail'
} catch (err) {
echo "Caught: ${err}"
currentBuild.result = 'FAILURE'
} finally {
sh './tear-down.sh'
}
step([$class: 'Mailer', recipients: 'admin@somewhere'])
}

1
2
3
4
5
6
7
8
9
10
11
12
13
script{
try {
sh label: '', script: '''
curl -u ftpuser:123456 ftp://172.16.9.242/artifacts/60/ -X "MKD $JOB_NAME"
'''
}
catch (exc) {
echo '创建ftp文件夹失败,尝试能否上传成功'
}
finally {
sh '**********'
}
}

deleteDir:删除文件/文件夹

deleteDir()

dir:选择工作区

dir()

echo

echo 'hello'

error:自定义异常抛出

error 'an error'

fileExists:判断文件/文件夹是否存在

fileExists './dist'

isUnix:判断操作系统

1
2
3
4
isUnix()

false if Windows
true if linux

mail:邮件功能

1
mail bcc: '', body: '这是一个测试邮件', cc: 'l_hc@winning.com.cn', from: 'l_hc@winning.com.cn', replyTo: '', subject: '测试', to: 'l_hc@winning.com.cn'

pwd:返回文件路径

1
2
3
两种 显示当前 显示临时工作目录
pwd tmp: true
pwd()

readFile:

readFile encoding: 'utf-8', file: './ex1.txt'

retry:出现异常时重试

1
2
3
retry(5) {
// some block
}

sleep:

1
2
3
4
5
6
7
8
9
10
11
12
默认秒,和省略参数:
sleep 30
非默认值:
sleep time: 30, unit: 'NANOSECONDS'
可选择参数:
NANOSECONDS
MICROSECONDS
MILLISECONDS
SECONDS
MINUTES
HOURS
DAYS

timeout:超时停止

1
2
3
4
参数同上:
timeout(activity: true, time: 30, unit: 'NANOSECONDS') {
// some block
}

load

1
2
3
4
5
6
def pipeline
node('slave') {
pipeline = load 'pipeline.groovy'
pipeline.functionA()
}
pipeline.functionB()

node:脚本式 pipeline 指明运行的节点

1
2
3
node('master') {
// some block
}

node:可以更换缓存位置

1
2
3
4
5
6
7
8
9
10
11
nodejs('node-v10.16.3') {
// some block
}

nodejs(cacheLocationStrategy: executor(), nodeJSInstallationName: 'node-v10.16.3') {
// some block
}

nodejs(cacheLocationStrategy: workspace(), nodeJSInstallationName: 'node-v10.16.3') {
// some block
}

properties:job的设置

1
properties([disableConcurrentBuilds(), buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '3', numToKeepStr: '')), pipelineTriggers([cron('0 5 * * *')])])

sshpublisher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
sshPublisher(
publishers: [
sshPublisherDesc(
configName: '212开发服务主线',
transfers: [
sshTransfer(
cleanRemote: false,
excludes: '',
execCommand: '''cd /winning/app/html/$app_id \n unzip -o dist.zip \n nginx reload''',
execTimeout: 120000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: "/winning/app/html/$app_id",
remoteDirectorySDF: false,
removePrefix: "",
sourceFiles: "dist.zip")],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: false
)
]
)

stage

1
2
3
stage('num 1') {
// some block
}

unstable:不稳定构建显示信息

1
unstable 'Prints a message to the log and sets the overall build result and the stage result to UNSTABLE. The message will also be associated with the stage result and may be shown in visualizations.'

unstash:恢复之前保存的一组文件

unstash 'dist.zip'

validateDeclarativePipeline:验证包含声明性管道的文件,返回 trun | false

validateDeclarativePipeline ‘./dist’

waitUntil:重复运行

1
2
3
4
5
重复运行它的主体,直到它返回 true。 如果返回 false,则等待一段时间并再次尝试。 (接下来的失败会减慢两次尝试之间的延迟。) 
重试的次数没有限制,但是如果主体抛出一个立即抛出的错误。
waitUntil {
// some block
}

withCredentials:使用密匙

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
node {
withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
sh '''
set +x
curl -u "$USERPASS" https://private.server/ > output
'''
}
}
node {
withCredentials([string(credentialsId: 'mytoken', variable: 'TOKEN')]) {
sh '''
set +x
curl -H "Token: $TOKEN" https://some.api/
'''
}
}
node {
ws {
withCredentials([file(credentialsId: 'secret', variable: 'FILE')]) {
sh 'use $FILE'
}
}
}

withEnv:设置自定义环境变量

1
2
3
4
5
node {
withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
sh '$MYTOOL_HOME/bin/start'
}
}

withMaven:

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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
withMaven(
jdk: 'jdk8',
maven: 'maven-3.6.1',
mavenOpts: '-XX:-UseGCOverheadLimit -Xmx512M -Xms512M',
options: [
concordionPublisher(disabled: true),
findbugsPublisher(disabled: true),
dependenciesFingerprintPublisher(
disabled: true,
includeReleaseVersions: true,
includeScopeTest: true
includeScopeRuntime: false,
includeSnapshotVersions: false),
artifactsPublisher(disabled: true),
invokerPublisher(disabled: true),
jgivenPublisher(disabled: true),
jacocoPublisher(disabled: true),
junitPublisher(
disabled: true,
healthScaleFactor: 1.0,
ignoreAttachments: true),
mavenLinkerPublisher(disabled: true),
openTasksPublisher(disabled: true),
pipelineGraphPublisher(
disabled: true,
lifecycleThreshold: 'package'),
spotbugsPublisher(disabled: true)
]
)
{
// some block
}

注释:
concordionPublisher:
Publish Concordion reports, if found, regarding the given pattern.
Test results are by default published if the Jenkins HTMLPublisher Plugin is installed.
发布关于给定模式的 Concordion 报告(如果找到)。
如果安装了 Jenkins HTMLPublisher 插件,测试结果默认情况下是发布的。

findbugsPublisher:
Publish FindBugs reports generated by "org.codehaus.mojo:findbugs-maven-plugin:findbugs".
FindBugs results are by default published if the Jenkins FindBugs Plugin is installed.
发布由“ org.codehaus.mojo: FindBugs-maven-plugin: FindBugs”生成的 FindBugs 报告。
如果安装了 Jenkins FindBugs 插件,则默认情况下会发布 FindBugs 结果。
Configure the thresholds for the build health. If left empty then no health report is created. If the actual number of warnings is between the provided thresholds then the build health is interpolated.
配置构建健康状况的阈值。 如果保持空白,则不会创建健康报告。 如果警告的实际数量介于所提供的阈值之间,那么构建健康状况就会被内插。
findbugsPublisher(disabled: true, healthy: '60', unHealthy: '50'),
Determines which warning priorities should be considered when evaluating the build health.
确定在评估构建健康状况时应考虑哪些警告优先级

dependenciesFingerprintPublisher:
Fingerprint the Maven dependencies used by the maven project.
指纹化 Maven 项目使用的 Maven 依赖项。

artifactsPublisher:
Archive and fingerprint the artifact and the attached artifacts generated by the maven project.
将 maven 项目生成的工件和附加工件存档并指纹识别。

invokerPublisher:
Publish Invoker reports generated by "org.apache.maven.plugins:maven-invoker-plugin:run".
Invoker results are by default published if the Jenkins Maven Invoker Plugin is installed.
发布由“org.apache.maven.plugins: maven-Invoker-plugin: run”生成的 Invoker 报告。
如果安装了 Jenkins Maven Invoker Plugin,则默认情况下会发布 Invoker 结果。

jgivenPublisher:
Publish JGiven reports, if found.
Test results are by default published if the Jenkins JGiven Plugin is installed.
发布 JGiven 报告,如果找到的话。 如果安装了 Jenkins JGiven 插件,则默认情况下会发布测试结果。

jacocoPublisher:
Publish JaCoCo Java Code Coverage Library reports, if found.
Test results are by default published if the Jenkins JaCoCo Plugin is installed.
如果找到,则发布 JaCoCo Java 代码覆盖库报告。
如果安装了 Jenkins JaCoCo Plugin,则默认情况下会发布测试结果。

junitPublisher:
Publish JaCoCo Java Code Coverage Library reports, if found.
Test results are by default published if the Jenkins JaCoCo Plugin is installed.
如果找到,则发布 JaCoCo Java 代码覆盖库报告。
如果安装了 Jenkins JaCoCo Plugin,则默认情况下会发布测试结果。
ignoreAttachments:
Skip the publishing of tests reports attachments.
Test result attachments are by default published if the Jenkins JUnit Attachments Plugin is installed.
跳过发布测试报告附件。
如果安装了 Jenkins JUnit 附件插件,则默认情况下会发布测试结果附件。
Health report amplification factor:
The amplification factor to apply to test failures when computing the test result contribution to the build health score.
当计算测试结果对构建健康评分的贡献时,增益应用于测试失败。
The factor is persisted with the build results, so changes will only be reflected in new builds.
该因素将与构建结果保持一致,因此更改将只反映在新的构建中。
Retain long standard output/error:
If checked, any standard output or error from a test suite will be retained in the test results after the build completes. (This refers only to additional messages printed to console, not to a failure stack trace.) Such output is always kept if the test failed, but by default lengthy output from passing tests is truncated to save space. Check this option if you need to see every log message from even passing tests, but beware that Jenkins's memory consumption can substantially increase as a result, even if you never look at the test results!
如果勾选此选项,则在构建完成后,测试套件中的任何标准输出或错误都将保留在测试结果中。 (这只引用打印到控制台的附加消息,而不引用失败堆栈跟踪。) 如果测试失败,则始终保留这样的输出,但默认情况下,通过测试的冗长输出会被截断以节省空间。 如果您需要查看来自甚至通过测试的所有日志消息,请选中此选项,但要注意,即使您从未查看测试结果,Jenkins 的内存消耗也会因此大幅增加!

mavenLinkerPublisher:
This publisher generates and publishes the links (url) of deployed Maven artifacts.
该发布者生成并发布已部署的 Maven 构件的链接(url)。

openTasksPublisher:
Publish Open Task Scanner reports.
Open Task Scanner reports are by default published if the Jenkins Task Scanner Plugin is installed.
The default setup is to look in Java source code for "FIXME" comments as high priority tasks and for "TODO" comments as normal priority tasks.
发布打开的任务扫描器报告。
如果安装了 Jenkins 任务扫描器插件,则默认情况下会发布打开任务扫描器报告。
默认设置是在 Java 源代码中查找“ FIXME”注释作为高优先级任务,“ TODO”注释作为普通优先级任务。

pipelineGraphPublisher:
Build a graph of pipelines based on their Maven dependencies and on the Maven artifacts they generate.
根据它们的 Maven 依赖项和它们生成的 Maven 构件构建一个管道图。

spotbugsPublisher:
Publish SpotBugs reports generated by "com.github.spotbugs:spotbugs-maven-plugin:spotbugs".
SpotBugs results are by default published if the Jenkins FindBugs Plugin is installed.
发布“ com.github. SpotBugs: SpotBugs-maven-plugin: SpotBugs”生成的 SpotBugs 报告。
如果安装了 Jenkins FindBugs 插件,SpotBugs 的结果将默认发布。
Health thresholds:
Configure the thresholds for the build health. If left empty then no health report is created. If the actual number of warnings is between the provided thresholds then the build health is interpolated.
配置构建健康状况的阈值。 如果保持空白,则不会创建健康报告。 如果警告的实际数量介于所提供的阈值之间,那么构建健康状况就会被内插。
Health priorities:
Determines which warning priorities should be considered when evaluating the build health.
确定在评估构建健康状况时应考虑哪些警告优先级

writeFile:写入文件

1
writeFile encoding: 'utf-8', file: './dist', text: 'exexex'

ws:指定工作空间/并发的话

1
2
3
ws("$ WORKSPACE/$win_appname") {
// some block
}

milestone :

stash:

运维

换源

方案一

直接修改默认配置文件

1
2
3
4
[root@localhost ~]# find / -name "default.json"  
/var/lib/jenkins/updates/default.json
[root@localhost ~]# sed -i 's/http:\/\/updates.jenkins-ci.org\/download/https:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' /var/lib/jenkins/updates/default.json && sed -i 's/http:\/\/www.google.com/https:\/\/www.baidu.com/g' /var/lib/jenkins/updates/default.json
[root@localhost ~]# systemctl restart jenkins

方案二

在插件管理里面修改

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
jenkins插件清华大学镜像地址:
https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json

更换地址方法
1.进入jenkins系统管理
2.进入插件管理
3.高级
4.修改 https:/mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json 为 https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json
5.提交
6.获取当前状态


有的时候更换镜像之后下载插件还是走的官方地址
原因:配置了清华的镜像之后他还是走的jenkins官方去拉取的,是因为清华镜像的配置文件里面的插件下载地址并不是指向的清华镜像,仍然指向的是jenkins官方的地址,我的解决方案是把jenkins官方的地址通过nginx吞掉直接转发到清华镜像去。
host配置

127.0.0.1 updates.jenkins-ci.org
1
nginx配置

rewrite ^/download/plugins/(.*)$ https://mirrors.tuna.tsinghua.edu.cn/jenkins/plugins/$1? last;
1


location /download/plugins
{
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_set_header Host mirrors.tuna.tsinghua.edu.cn;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite /download/plugins(.*) /jenkins/plugins/$1 break;
proxy_pass https://mirrors.tuna.tsinghua.edu.cn;
}

解决:可以通过在nginx上配置代理,将官方的插件下载地址映射到 https://mirrors.tuna.tsinghua.edu.cn/jenkins/plugins/
这样下载插件也会从镜像网站下载

案例分享

图解:利用PostMan+Newman+Jenkins实现Web API持续集成

mark

喜欢这篇文章?打赏一下作者吧!

欢迎关注我的其它发布渠道