本次小节说一下Jenkins-pipline。pipline是运行在Jenkins2.X版本的核心插件,简单来说pipline就是一套运行于Jenkins上的工作流框架,将原本独立运行单个或者多个节点的任务连接起来,实现单个任务难以完成的复杂发布流程。
pipline语法:
stage:阶段,一个pipline中可以划分多个stage,每个stage都是一个操作步骤(可以在视图中查看到),阶段是一个逻辑分组,可以跨多个node执行。
node:节点,每一个node都是Jenkins节点,可以是Jenkins-master也可以是Jenkins-save,node就是执行step的具体服务器。
step:步骤,step是Jenkins-pipline最基本的操作单元,既step等于一个或者多个执行操作的步骤,一个stage中可以有多个step,如sh **.bash
pipline优势:
可持续性:Jenkins的重启或者中断后不影响已经执行的pipline job。
支持暂停:pipline可以选择停止并等待人工输入或者批准后在执行
并行执行:通过groovy脚本可以实现step,stage间的并行执行
pipline语法:
声明式:
pipeline {
agent any //
stages {
stage('Build') {
steps {
//
}
}
stage('Test') {
steps {
//
}
}
stage('Deploy') {
steps {
//
}
}
}
}
agent any: 任意可用的agent都可以执行
stages:代表整个流水线的所有执行阶段。通常stages只有1个,里面包含多个stage
stage:代表流水线中的某个阶段,可能出现n个。一般分为拉取代码,编译构建,部署等阶段。
steps:代表一个阶段内需要执行的逻辑。steps里面是shell脚本,git拉取代码,ssh远程发布等任意内容。
脚本式:
node {
stage('Build') {
//
}
stage('Test') {
//
}
stage('Deploy') {
//
}
}
node:节点,一个 Node 就是一个 Jenkins 节点,Master 或者 Agent,是执行 Step 的具体运行环境
Stage:阶段,一个 Pipeline 可以划分为若干个 Stage,每个 Stage 代表一组操作,比如:Build、Test、Deploy,Stage 是一个逻辑分组的概念。
声明式和脚本式的主要区别:
声明式pipline会在执行之前就会校检pipline语法是否正确,而脚本式不会
观察下面声明式例子,stage Test 里面的 ‘echo 1’ 有语法错误,echo 只可以接受字符串,尝试执行该 pipeline时,会立即报错
pipeline {
agent any
stages {
stage("Build") {
steps {
echo "Some code compilation here..."
}
}
stage("Test") {
steps {
echo "Some tests execution here..."
echo 1
}
}
}
}

同样脚本式的例子如下,会执行到stage Test才会报错
node {
stage("Build") {
echo "Some code compilation here..."
}
stage("Test") {
echo "Some tests execution here..."
echo 1
}
}

想象一下如果有多个 stage,前面的stage 执行都没有问题而最后一个stage 出问题,这将会浪费一定的时间
如果某个 stage 执行失败,修复后声明式 Pipeline 可以直接跳到该 stage 重新执行,而脚本式要从头来过。
pipline语法之if判断:
pipeline {
agent any
stages {
stage("check file if exists"){ #执行此步的名称
steps{
script{
out=sh(script:"ls /tmp/uu.txt",returnStatus:true)
println "--------------"
println out
if(out == 0){
println "file is exist" #println 类似于java语法:打印并回车
}else if(out == 2){
println "file is not exist"
}else{
error("command is error,please check") #命令有误一般状态码为127
}
}
}
}
}
}
sh(script:"ls /tmp/uu.txt",returnStatus:true)
sh执行一个shell,脚本内容:ls /tmp/uu.txt returnStatus:true 返回结果的状态吗,还有一个常用的参数 returnStdout:true 它返回的是结果的输出