Jenkins 配置 Pipeline 脚本
Jenkinsfile支持两种语法形式
Scripted pipeline - 脚本式流水线语法,基于 Groovy语言构建的通用 DSL(Domain-specific language,领域特定语言)
Declarative pipeline - 声明式流水线语法,在v2.5之后引入,支持结构化方式,提供了更丰富的语法特性
Scripted pipeline 可以把 pipeline 代码写在 Script 区域
Declarative pipeline 方式可以把 Pipeline 脚本放在 git 仓库中,构建时执行 git 命令,切换到需要构建的分支
Declarative pipeline
声明式流水线语法必须包含在一个 pipeline块内:
pipeline {
/* Declarative Pipeline */
}
pipeline块中主要由Sections, Directives, Steps, 或者赋值语句组成
Sections
Sections包括 agent、stages、steps、post
agent定义 pipeline执行节点,必须在pipeline 块的顶层定义
主要参数:
any:可以在任意可用的 agent上执行pipeline
none:pipeline将不分配全局agent,每个 stage分配自己的agent
label:指定运行节点agent的 Label
node:自定义运行节点配置
stages
包含一个或多个 stage
Pipeline的大部分工作在此执行。
stages 也是必须指定的指令,没有参数
此外,每个 pipeline块中必须只有一个 stages
stage也必须指定,需要定义stage的名字:
steps
steps位于stage块中,也是必须设置的指令,无参数
steps块中可以包含script块,可用于存放Scripted Pipeline 脚本
post
post是在Pipeline或者 stage执行结束后的操作,不是必须出现的指令,可设置以下触发条件
always:无论 Pipeline或者stage运行完成的状态如何都会运行
changed:只有当前 Pipeline或者stage运行的状态与先前运行状态不同时才能运行
fixed:只有当前一次构建失败或者不稳定,而当前 Pipeline或者stage运行成功时运行
regression:前一次运行成功,而当前Pipeline或者stage运行状态为failure, unstable 或者 aborted时运行
aborted:只有当前 Pipeline或者stage处于“aborted”状态时才能运行。通常是手动终止。
failure:当前 Pipeline或者stage处于“failed”状态时才运行
success:当前 Pipeline或者stage具有“success”状态时才运行
unstable:当前 Pipeline或者stage具有“unstable”状态才运行
unsuccessful:当前 Pipeline或者stage不是“success”状态时运行
cleanup:不管Pipeline或stage的状态如何,在每一个post条件被执行之后运行
一个样例如下
fileUrl="AAAAAA"
pipeline {
agent any
// 全局变量
environment {
Name = "ABC"
}
stages {
stage('Print WorkSpace') {
steps {
script {
echo "Hello world"
echo "当前的工作目录: ${env.WORKSPACE}"
echo "BRANCH_NAME: ${env.BRANCH_NAME}"
}
}
}
stage('Test') {
steps {
script {
echo "stage Test"
}
}
}
}
// 流水线 stage 执行结束后调用 post
post {
// 执行到 post,无论运行状态是完成还是失败,都会第一个调用 always
always {
script {
echo "${fileUrl}"
fileUrl = "BBBBBB"
echo "Name=${Name}"
echo "This will always run, regardless of success or failure."
}
}
// 流水线执行成功调用 success
success {
script {
echo "${fileUrl}"
fileUrl = "CCCCCC"
// 如果构建成功,执行的脚本
echo "Build succeeded!"
// 可以在这里执行更多的操作,例如发送成功通知
}
}
// 流水线执行失败调用 failure
failure{
script {
echo "${fileUrl}"
fileUrl = "DDDDDD"
// 如果构建失败,执行的脚本
echo "Build failed!"
// 可以在这里执行更多的操作,例如发送失败通知
}
}
// 手动终止执行调用 aborted
aborted {
script {
echo "Aborted"
}
}
}
}