jenkins教程:jenkinsfile语法之stages、steps和post

jenkins教程:jenkinsfile语法之stages、steps和post_chrome

stages

包含一个或多个 stage, Pipeline的大部分工作在此执行。stages也是必须指定的指令,没有参数。此外,每个 pipeline块中必须只有一个 stages。

stage也必须指定,需要定义stage的名字:

pipeline {
    agent any
    stages {
        stage('init') {
            steps {
                echo 'Hello World'
            }
        }
    }
}
steps

steps位于stage块中,也是必须设置的指令,无参数。

steps块中可以包含script块,可用于存放Scripted Pipeline 脚本:

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'

                script {
                    def browsers = ['chrome', 'firefox']
                    for (int i = 0; i < browsers.size(); ++i) {
                        echo "Testing the ${browsers[i]} browser"
                    }
                }
            }
        }
    }
}
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条件被执行之后运行。

示例脚本:

pipeline {
    agent any
    stages {
        stage('init') {
            steps {
                echo 'Hello World'
            }
        }
    }
    post {
        success {
            echo 'success!'
            sleep 2        
        }

        always {
            echo 'goodbye'
        }
    }
}