Jenkinsfile是Jenkins2.x版本推出流水线pipeline之后的配置文件,可以将构建过程全部以代码的形式写在Jenkinsfile里面,Jenkinsfile随代码库一起进行维护。关于Jenkinsfile的更多信息请查看Jenkins官网。
流水线
流水线是Jenkins2.x版本推出的新特性,按照其字面意思理解,将软件的生产过程与传统工艺的生产过程相比较,从原料(code)到完整的,可交付的产品,中间不需要人工进行干预。
流水线支持两种语法, 声明式 (在流水线 2.5 引入)和脚本化流水线。 两种都支持构建持续交付流水线。两种都可以用来在 web UI 或 Jenkinsfile 中定义流水线, 不过通常认为创建一个 Jenkinsfile 并将其检入带源代码控制仓库是最佳实践。
建议着重理解下声明式和脚本化,在刚开始接触流水线时,通过Web UI上创建的,node开头的,为脚本化流水线。所有code都写在pipeline块里面的,为声明式流水线。
本文以声明式流水线为例
声明式流水线
声明式流水线所有有效的内容必须包含在一个pipeline
块中
pipeline {
/* insert Declarative Pipeline here */
}
Sections
agent
agent
指定了整个流水线或特定的stage将会在Jenkins的哪个节点执行,这取决于 agent 区域的位置。agent
必须在 pipeline 块的顶层被定义, 在 stage 级别的定义是可选的。
参数:
- any:在任何可用的节点上执行流水线或stage部分。
pipeline {
agent any
}
- none:当
agent
在pipeline的顶层被设置为none时,那么在每个stage中都需要添加agent,并指定构建节点。
pipeline {
agent none
stages {
stage('Example Build') {
agent any
steps {
'do some thing'
}
}
}
}
- label:选择特定标签的Jenkins节点作为构建环境。
pipeline {
agent { label 'my-defined-label' }
}
- node:node用法与label用法一样,但是node有额外的可选参数
customWorkspace
,可以指定工作空间。
pipeline {
agent {
node {
label 'my-defined-label'
customWorkspace '/some/other/path'
}
}
}
- docker:使用指定的容器进行构建,该参数需要结合
node
或者label
进行使用,以便指定在哪个节点上执行docker。该选项可以添加args参数,args参数将直接传递给docker run
,alwaysPull 则强制docker执行pull,即使镜像名称已经存在。
pipeline {
agent {
docker {
image 'maven:3-alpine'
label 'my-defined-label'
args '-v /tmp:/tmp'
}
}
}
- dockerfile:使用源代码库中已有的Dcoekrfile构建的容器来进行构建。要使用该选项, Jenkinsfile 必须从多个分支流水线中加载或者选择 "Pipeline from SCM."选项。
pipeline {
agent {
// Equivalent to "docker build -f Do