Jenkins-流水线常用配置
1. 设置BuildName
1.1. Job构建环境选项
1
2
3
构建环境 --> Set Build Name --> Build Name --> Build Description
Build Name: 构建标号,设置的参数
#${BUILD_NUMBER}-[${method}]
1.2. Pipline
在 Jenkins Pipeline 中设置构建名称可以通过 currentBuild.displayName 属性实现。你可以在任何阶段的脚本步骤中设置这个属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
pipeline {
agent any
stages {
stage("Show Params"){
steps {
script {
currentBuild.displayName = "$BUILD_NUMBER $serviceName on $branch"
currentBuild.description = "$releaseVersion"
}
}
}
}
}
2. 设置环境变量
引用参数; Jenkins 系统变量: //凭据 –> 系统 –> 全局凭据
1
2
3
4
5
6
7
8
9
10
11
pipeline {
agent any
environment {
actionLogId = "$params.actionLogId"
branch = "$params.branch"
serviceName = "$params.serviceName"
releaseVersion = "$params.releaseVersion"
HTTP_BLUEKING_TOKEN=credentials('CMDB_TOKEN')
}
}
3. 构建日志中添加时间戳
时间戳格式: HH:mm:ss.SSS, 固定无法修改
1
2
3
4
5
6
7
pipeline {
agent any
options {
timestamps()
}
}
4. 调用其他的Job
使用方式,解释:
- 通过 build 步骤触发名为 OtherJob 的 Job,并且等待它执行完成:
1 build job: 'OtherJob', wait: true- 使用 rawBuild.getLog() 方法获取该 Job 最新的 50 行日志:
1 downstreamJob.rawBuild.getLog(50)- 将获取到的日志输出到当前的 Job 控制台:
1 echo consoleOutput.join("\n")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 pipeline { agent any stages { stage('Trigger Another Job') { steps { script { // 调用其他 Job def downstreamJob = build job: 'OtherJob', wait: true // 获取该 Job 的日志 def consoleOutput = downstreamJob.rawBuild.getLog(50) // 获取最新的 50 行日志 echo "Logs from OtherJob:" echo consoleOutput.join("\n") // 打印日志 } } } } }======================================================================
特殊使用:
- 异步调用:
1 build job: 'OtherJob', wait: false- 获取所有日志:
a.使用 getLog() 方法不传参数;
b.使用 getLogText() 结合 readAll() 读取完整日志;
1 2 3 def consoleOutput = downstreamJob.rawBuild.getLogText().readAll() echo "Complete logs from OtherJob:" echo consoleOutput- 获取子任务的结果和状态
1 2 3 4 5 if (downstreamJob.result == 'SUCCESS') { echo "OtherJob completed successfully!" } else { echo "OtherJob failed!" }
5.逻辑组合器
5.1 allOf
表示所有内部条件都必须满足
相当于逻辑 AND 操作,和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 stage('Your Stage Name') { when { allOf { expression { IS_TAG_BUILD.toBoolean() } expression { def regions = readJSON text: env.REGION_INFO ?: '{}' return !regions.isEmpty() } } } steps { // 您的步骤内容 } }
5.2 anyOf
表示所有内部条件有一个满足就好
相当于 OR,或
1 2 3 4 5 6 when { anyOf { expression { IS_TAG_BUILD.toBoolean() } expression { env.SKIP_CHECK == 'true' } } }
5.3 not
表示内部条件都不满足
相当于逻辑 NOT 操作,非
1 2 3 4 5 when { not { triggeredBy 'TimerTrigger' } }
5.5 复杂使用
白名单+黑名单控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 when { expression { def regions = readJSON text: env.REGION_MAP ?: '{}' allOf { // 必须满足所有条件: not { expression { regions.isEmpty() } } // 条件1:非空 anyOf { // 条件2.1:含非cn区域 expression { regions.keySet().any { it != 'cn' } } // 条件2.2:cn的value符合要求 expression { regions.cn == 'cn-beijing-8' } } } } }
本文由作者按照
CC BY 4.0
进行授权