越来越强大的Jenkins
Jenkins Pipeline支持的指令
指令名 | 说明 | 作用域 |
---|---|---|
agent | 定义执行任务的代理 | stage 或pipeline |
environment | 设置环境变量 | stage或pipeline |
tools | 自动下载并安装指定的工具,并将其加入到PATH变量中 | stage或pipeline |
input | 暂停pipeline,提示输入内容 | stage |
options | 配置Jenkins pipeline本身,如options{retry(3}},指pipeline失败时再重试2次 | stage 或 pipeline |
parallel | 并行执行多个step | stage |
parameters | 执行pipeline前传入一些参数 | pipeline |
triggers | 定义执行pipeline的触发器 | pipeline |
when | 定义阶段执行的条件 | stage |
build | 触发其他的job | steps |
options Jenkins Pipeline配置参数
参数名 | 说明 | 例子 |
---|---|---|
buildDiscarder | 保留最近历史构建记录的数量 | buildDiscarder(logRotator(numToKeepStr: '10') |
checkoutToSubdirectory | 将代码从版本控制库中拉取后,保存在工作目录的子目录 | checkoutToSubdirectory('subdir') |
disableConcurrentBuilds | 禁用Jenkins同时执行多次该pipeline | disableConcurrentBuilds() |
newContainerPerStage | agent为Docker或Dockerfile时,每个stage都分别运行在一个新容器中 | newContainerPerStage() |
retry | pipeline发生失败后重试次数 | retry(4) |
timeout | pipeline运行超时时间 | timeout(time:10, unit: 'HOURS') |
pipeline{
agent any
options{
buildDiscarder(logRotator(numToKeepStr: '10')
disableConcurrentBuilds()
retry(4)
timeout(time:10, unit: 'HOURS')
}
stages{
stage('demo'){
steps{
sh 'echo hello'
}
}
}
}
stage间通过stash进行文件共享,即使stage不在同一个执行主机上
pipeline{
agent none
stages{
stage('stash'){
agent { label "master" }
steps{
writeFile file: "a.txt", text: "$BUILD_NUMBER"
stash name: "abc", includes: "a.txt"
}
}
stage('unstash'){
agent { label "node" }
steps{
script{
unstash("abc")
def content = readFile("a.txt")
echo "${content}"
}
}
}
}
}
steps中的一些操作
命令名 | 说明 |
---|---|
error | 抛出异常,中断整个pipeline |
timeout | timeout闭包内运行的步骤超时时间 |
waitUntil | 一直循环运行闭包内容,直到return true,经常与timeout同时使用 |
retry | 闭包内脚本重复执行次数 |
sleep | 暂停pipeline一段时间,单位为秒 |
pipeline{
agent any
stages{
stage('stash'){
steps{
timeout(50){
waitUntil{
script{
def r = sh script: 'curl http://xxx', returnStatus: true
return (r == 0)
}
}
}
retry(10){
script{
sh script: 'curl http://xxx', returnStatus: true
}
}
sleep(20)
}
}
}
post{
always{
echo "结束job"
}
}
}
来一个相对复杂一点的交互式Pipeline
pipeline{
agent any
triggers{
upstream(upstreamProjects: 'job1,job2', threshold: hudson.model.Result.SUCCESS)
}
stages{
stage('pre deploy'){
steps{
script{
BRANCHES = sh returnStdout: true, script: 'git branch -r | grep -v HEAD > out.txt; git tag >> out.txt; cat out.txt;'
dataMap = input message: '准备发布到哪个环境', ok: '确定', parameters: [choice(choices: ['dev', 'sit', 'prod'], description: '部署环境', name: 'ENV'), choice(choices: "${BRANCHES}", description: '分支', name: 'TAG')], submitterParameter: 'APPROVER'
}
}
}
stage("演示一下"){
steps{
echo "${dataMap['APPROVER']}"
echo "${dataMap['ENV']}"
echo "${dataMap['TAG']}"
}
}
}
}
共享库share library
解决问题:
- pipeline不出现方法定义,把所有类库写到library中
- pipeline中重复步骤可以写到library中
- 规范流程过程
例子:https://github.com/liwei2151284/jenkins_library
参考文章:https://testerhome.com/topics/10782
- 系统设置中设置global pipeline libraries,名字为jenkins_library,添加git地址共享库
- 使用:
library "jenkins_library"
node {
stage("test"){
sayHello()
}
}
参考资料
《Jenkins 2.X实践指南》