一、语法结构
Jenkins 2.5新加入的pipeline语法
声明式pipeline 基本语法和表达式遵循 groovy语法,但是有以下例外:
- 声明式pipeline 必须包含在固定格式的pipeline{}中
- 每个声明语句必须独立一行, 行尾无需使用分号
- 块(Blocks{}) 只能包含章节(Sections),指令(Directives),步骤(Steps),或者赋值语句
- 属性引用语句被视为无参数方法调用。 如input()
一个声明式Pipeline中包含的元素
- pipeline:声明这是一个声明式的pipeline脚本
- agent:指定要执行该Pipeline的节点(job运行的slave或者master节点)
- stages:阶段集合,包裹所有的阶段(例如:打包,部署等各个阶段)
- stage:阶段,被stages包裹,一个stages可以有多个stage
- steps:步骤,为每个阶段的最小执行单元,被stage包裹
- post:执行构建后的操作,根据构建结果来执行对应的操作
示例:
pipeline{
// 指定pipeline在哪个slave节点上允许
agent { label 'jdk-maven' }
// 指定pipeline运行时的一些配置
option {
timeout(time: 1, unit: 'HOURS')
}
// 自定义的参数
parameters {
string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
text(name: 'BIOGRAPHY', defaultValue: '', description: 'Enter some information about the person')
booleanParam(name: 'TOGGLE', defaultValue: true, description: 'Toggle this value')
choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')
password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'Enter a password')
}
// 自定义的环境变量
environment {
Gitlab_Deploy_KEY = credentials('gitlab-jenkins-depolykey')
}
// 定义pipeline的阶段任务
stages {
stage ("阶段1任务:拉代码") {
steps {
// 拉代码的具体命令
}
}
stage ("阶段2任务:编译代码") {
steps {
// 编译代码的具体命令
}
}
stage ("阶段3任务:扫描代码") {
steps {
// 拉代码的具体命令
}
}
stage ("阶段4任务:打包代码") {
steps {
// 打包代码的具体命令
}
}
stage ("阶段5任务:构建推送Docker镜像") {
steps {
// 构建推送Docker镜像的具体命令
}
}
stage ("阶段6任务:部署镜像") {
steps {
// 部署镜像的具体命令
}
}
}
post {
success {
// 当pipeline构建状态为"success"时要执行的事情
}
always {
// 无论pipeline构建状态是什么都要执行的事情
}
}
}
二、章节Sections
1、agent(必须)
指定整个Pipeline或特定阶段是在Jenkins Master节点还是Jenkins Slave节点上运行。可在顶级pipeline
块和每个stage
块中使用(在顶层pipeline{}
中是必须定义的 ,但在阶段Stage中是可选的)
参数(以下参数值在顶层pipeline{}
和stage{}
中都可使用):
- any:在任何可用的节点上执行Pipeline或Stage
- none:当在
顶层pipeline{}
中应用时,将不会为整个Pipeline运行分配全局代理,并且每个stage
部分将需要包含其自己的agent
部分 - label
- node
- docker
- dockerfile
- kubernetes
公用参数:
- label
- customWorkspace
- reuseNode
- args
2、post
定义在Pipeline运行或阶段结束时要运行的操作。具体取决于Pipeline的状态
支持pipeline运行状态:
- always:无论Pipeline运行的完成状态如何都要运行
- changed:只有当前Pipeline运行的状态与先前完成的Pipeline的状态不同时,才能运行
- fixed:整个pipeline或者stage相对于上一次失败或不稳定Pipeline的状态有改变。才能运行
- regression:
- aborted:只有当前Pipeline处于“中止”状态时,才会运行,通常是由于Pipeline被手动中止(通常在具有灰色指示的Web UI 中表示)
- failure:仅当当前Pipeline处于“失败”状态时才运行(通常在Web UI中用红色指示表示)
- success:仅当当前Pipeline在“成功”状态时才运行(通常在具有蓝色或绿色指示的Web UI中表示)
- unstable:只有当前Pipeline在不稳定”状态,通常由测试失败,代码违例等引起,才能运行(通常在具有黄色指示的Web UI中表示)
- unsuccessful:
- cleanup:无论Pipeline或stage的状态如何,在跑完所有其他的
post
条件后运行此条件下 的post
步骤。
3、stages(必须)
- 至少包含一个用于执行任务的
stage
指令 pipeline{ }
中只能有一个stages{}
4、steps(必须)
- 在
stage
指令中至少包含一个用于执行命令的steps