一、Sections¶
声明式流水线中的 Sections 不是一个关键字或指令,而是包含一个或多个 Agent、Stages、 post、Directives 和 Steps 的代码区域块。
二、Post¶
Post 一般用于流水线结束后的进一步处理,比如错误通知等。Post 可以针对流水线不同的结 果做出不同的处理,就像开发程序的错误处理,比如 Python 语言的 try catch。Post 可以定义在 Pipeline 或 stage 中,目前支持以下条件:
- always:无论 Pipeline 或 stage 的完成状态如何,都允许运行该 post 中定义的指令;
- changed:只有当前 Pipeline 或 stage 的完成状态与它之前的运行不同时,才允许在该 post 部分运行该步骤;
- fixed:当本次 Pipeline 或 stage 成功,且上一次构建是失败或不稳定时,允许运行该 post 中定义的指令;
- regression:当本次 Pipeline 或 stage 的状态为失败、不稳定或终止,且上一次构建的状态为成功时,允许运行该 post 中定义的指令;
- failure:只有当前 Pipeline 或 stage 的完成状态为失败(failure),才允许在 post 部分运行该步骤,通常这时在 Web 界面中显示为红色;
- success:当前状态为成功(success),执行 post 步骤,通常在 Web 界面中显示为蓝色或绿色;
- unstable:当前状态为不稳定(unstable),执行 post 步骤,通常由于测试失败或代码违规等造成,在 Web 界面中显示为黄色;
- aborted:当前状态为终止(aborted),执行该post步骤,通常由于流水线被手动终止 触发,这时在 Web 界面中显示为灰色;
- unsuccessful:当前状态不是 success 时,执行该 post 步骤;
- cleanup:无论 pipeline 或 stage 的完成状态如何,都允许运行该 post 中定义的指令。 和 always 的区别在于,cleanup 会在其它执行之后执行。
示例:一般情况下 post 部分放在流水线的底部,比如本实例,无论 stage 的完成状态如何, 都会输出一条I will always say Hello again!信息:
// Jenkinsfile (Declarative Pipeline) // 可以不写该行
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
post {
always {
echo 'I will always say Hello again!'
}
}
}
也可以将 post 写在 stage:
pipeline {
agent any
stages {
stage('Test') {
steps {
sh 'EXECUTE_TEST_COMMAND'
}
post {
failure {
echo "Pipeline Testing failure..."
}
}
}
}
}
三、Stages¶
Stages 包含一个或多个 stage 指令,同时可以在 stage 中的 steps 块中定义真正执行的指令。
stages部分是流水线描述的大部分工作(work)的位置。建议stages至少包含一个stage指令,用于持续交付过程的某个离散的部分,比如构建、测试或部署。
比如创建一个流水线,stages包含一个名为Example的stage,该stage执行echo 'Hello World'命令输出Hello World字符串:
// Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
stages {
stage('Example') {
steps {
echo "Hello World ${env.BUILD_ID}"
}
}
}
}
四、Steps¶
steps部分在给定的stage指令中执行一个或多个步骤,比如在steps中定义执行一条shell命令:
// Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
}
或者是使用 sh 字段执行多条指令:
Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
stages {
stage('Example') {
steps {
sh """
echo 'Execute building...'
mvn clean install
"""
}
}
}
}