相关文章推荐
精明的核桃  ·  dotnet add reference ...·  1 年前    · 
含蓄的大象  ·  Anaconda使用教程 - ...·  2 年前    · 
怕老婆的卤蛋  ·  OpenCV-android-sdk ...·  3 年前    · 

Jenkinsfile以stage为逻辑功能实现和划分的方式使用起来非常方便,而一旦发生异常之后应该如何处理,如何根据stage执行的结果而进行特定处理则是实际Pipeline使用中经常会碰到的问题。在Groovy或者Java语言中一般这就是try {} catch{}的使用场景,而Jenkinsfile也将执行结果的状态进行共通化,可以根据执行结果的特定状态作为触发的条件,这就是post{}。而流水线的实现则只需要在对应的状态中执行预定的处理逻辑即可,这篇文章中将通过具体的示例进行介绍和演示。

post{}

根据执行记的结果决定处理内容,就像Java程序中catch块中做的那样,post{}根据pipeline或者stage的执行结果预先定义了多个条件,通过在流水线中声明这些条件和在这些条件之下的steps操作即可,类似回调函数的使用方法,你也可以把它看作是try…catch…的封装实现,从而使得对于异常的处理更加方便。

  • 使用限制:需要写在pipeline或者stage块中
  • 可选vs必选:可选
  • 支持的条件预置:
    • always: 无论pipeline或者stage的执行结果如何,此块中的预置操作都会执行。
    • changed:只有当pipeline或者stage的执行后,当前状态与之前发生了改变时,此块中的预置操作才会执行。
    • fixed:前一次运行为不稳定状态或者失败状态,而且本次运行成功结束,这两个条件同时满足时,此块中的预置操作才会执行。
    • regression: 本次运行状态为不稳定状态,失败状态或者是中止状态,而且前一次运行成功结束,这两个条件同时满足时,此块中的预置操作才会执行。
    • aborted:当前pipeline或者stage的状态为aborted时,此块中的预置操作才会执行。通常是由于流水线被手工中会导致此状态产生,而产生此状态后,通常在Jenkins的UI界面会显示为灰色。
    • failure:当前pipeline或者stage的状态为failed时,此块中的预置操作才会执行。而产生此状态后,通常在Jenkins的UI界面会显示为红色。
    • success:当前pipeline或者stage的状态为success时,此块中的预置操作才会执行。而产生此状态后,通常在Jenkins的UI界面会显示为绿色。
    • unstable: 当前pipeline或者stage的状态为unstable时,此块中的预置操作才会执行。通常情况下测试失败或者代码规约的违反都会导致此状态产生,而产生此状态后,通常在Jenkins的UI界面会显示为黄色。
    • unsuccessful:当前pipeline或者stage的状态不是success时,此块中的预置操作才会执行。
    • cleanup:无论pipeline或者stage的状态为何种状态,在post中的其他的条件预置操作执行之后,此块中的预置操作就会执行。

注意: cleanup和always的区别在于,cleanup会在其他任意一个条件预置操作执行之后就会执行。

本文示例:
将流水线分按照功能分为逻辑上的三段:构建(Build) 、测试(Test)、部署(Deploy),顺序如下所示。

本文使用Easypack的LTS Jenkins 2.176.1版,环境准备请参看

全局工具设定

全集工具设定可以通过XML配置文件的方式,也可以直接在Jenkins的管理界面进行操作,详细可参照:

获取Jenkins-Crumb

使用如下示例代码获取Jenkins-Crumb,为使用API方式为示例作准备。

liumiaocn:jenkins liumiao$ jenkins_host_url=http://localhost:32002
liumiaocn:jenkins liumiao$ user_passwd="root:liumiaocn"
liumiaocn:jenkins liumiao$ jenkins_crumb=`curl -u $user_passwd ${jenkins_host_url}'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)' 2>/dev/null`
liumiaocn:jenkins liumiao$ echo $jenkins_crumb
Jenkins-Crumb:83d748ee92512c4dccd589aaa5c55a9a
liumiaocn:jenkins liumiao$

创建Job

使用如下代码示例创建Job

liumiaocn:jenkins liumiao$ ls demo/pipeline/post/config.xml
demo/pipeline/post/config.xml
liumiaocn:jenkins liumiao$ cat demo/pipeline/post/config.xml
<?xml version='1.1' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@2.32">
  <actions>
    <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobAction plugin="pipeline-model-definition@1.3.8"/>
  </actions>
  <description>Pipeline Job Sample</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.plugins.jira.JiraProjectProperty plugin="jira@3.0.7"/>
    <com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty plugin="gitlab-plugin@1.5.12">
      <gitLabConnection></gitLabConnection>
    </com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty>
  </properties>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.69">
  <script>pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo Build stage ...'
            post {
	        	always {
	        		echo "post condition executed: always ..."
	        	changed {
	        		echo "post condition executed: changed ..."
	        	aborted {
	        		echo "post condition executed: aborted ..."
	        	regression {
	        		echo "post condition executed: regression ..."
        stage('Test'){
            steps {
                sh 'echo Test stage ...'
            post {
            	aborted {
            		echo "post condition executed: aborted ..."
            	failure {
            		echo "post condition executed: failure ..."
            	success {
            		echo "post condition executed: success ..."
        stage('Deploy') {
            steps {
                sh 'echo Deploy stage ...'
        post {
    	unstable {
    		echo "post condition executed: unstable ..."
    	unsuccessful {
    		echo "post condition executed: unsuccessful ..."
    	cleanup {
    		echo "post condition executed: cleanup ..."
  }</script>
  <sandbox>false</sandbox>
  </definition>
  <triggers/>
  <disabled>false</disabled>
</flow-definition>
liumiaocn:jenkins liumiao$ curl -X POST -u $user_passwd -H ${jenkins_crumb} -H "Content-Type:application/xml"  --data-binary  "@demo/pipeline/post/config.xml" ${jenkins_host_url}/createItem?name=pipeline_job_post
liumiaocn:jenkins liumiao$ echo $?
liumiaocn:jenkins liumiao$

Jenkinsfile说明

本文示例所使用的Jenkinsfile信息如下所示,内容非常简单易读,简单说明如下:

  • pipeline是结构,在其中可以指定agent和stages等相关信息
  • agent用于指定执行job的节点,any为不做限制
  • stages用与设定具体的stage
  • stage为具体的节点,比如本文示例中模拟实际的 Build(构建)、测试(Test)、部署(Deploy)的过程。
  • post中可以根据stage的执行结果进行错误处理
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo Build stage ...'
            post {
	        	always {
	        		echo "post condition executed: always ..."
	        	changed {
	        		echo "post condition executed: changed ..."
	        	aborted {
	        		echo "post condition executed: aborted ..."
	        	regression {
	        		echo "post condition executed: regression ..."
        stage('Test'){
            steps {
                sh 'echo Test stage ...'
            post {
            	aborted {
            		echo "post condition executed: aborted ..."
            	failure {
            		echo "post condition executed: failure ..."
            	success {
            		echo "post condition executed: success ..."
        stage('Deploy') {
            steps {
                sh 'echo Deploy stage ...'
        post {
    	unstable {
    		echo "post condition executed: unstable ..."
    	unsuccessful {
    		echo "post condition executed: unsuccessful ..."
    	cleanup {
    		echo "post condition executed: cleanup ..."

执行Job

使用如下命令或者直接在Jenkins上点击构建

liumiaocn:jenkins liumiao$ curl -X POST -u $user_passwd -H ${jenkins_crumb} ${jenkins_host_url}/job/pipeline_job_post/build
liumiaocn:jenkins liumiao$ echo $?
liumiaocn:jenkins liumiao$

确认执行结果

使用如下命令可以确认相关的执行日志信息

liumiaocn:jenkins liumiao$ curl -u $user_passwd ${jenkins_host_url}/job/pipeline_job_post/1/consoleText
Started by user root
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /data/jenkins/workspace/pipeline_job_post
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] sh
+ echo Build stage ...
Build stage ...
Post stage
[Pipeline] echo
post condition executed: always ...
[Pipeline] echo
post condition executed: changed ...
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] sh
+ echo Test stage ...
Test stage ...
Post stage
[Pipeline] echo
post condition executed: success ...
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Deploy)
[Pipeline] sh
+ echo Deploy stage ...
Deploy stage ...
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] echo
post condition executed: cleanup ...
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
liumiaocn:jenkins liumiao$

post用来做失败处理较为方便,一般来说会在末尾处进行处理,但是由于post实际上是支持pipeline或者stage的,在末尾的方式是pipeline块的post处理。的确,对失败进行统一处理的确是一种好的方式,但是也没有比较过于教条,正如我们使用try…catch那样,适合自己项目的方式才是最好的

https://jenkins.io/doc/book/pipeline/syntax/#tools

stage中设置catchError和post,当steps运行失败时,将stageResult设置为失败,通过post发送失败邮件通知。结果:steps执行失败时,catchError将stageResult设置为失败,但failurepost没有触发。某个stage失败不影响整体pipeline运行,只需要在stage失败时邮件通知相关人员即可。post支持根据stage核pipeline执行的结果而进行特定处理,但在post。在failurepost前需要加一个always触发post。 PyCharm Jenkinsfile语法突出显示支持 将Jenkinsfile.xml复制到您的filetypes文件夹中,然后重新启动PyCharm 2019.3.x及以下版本 ~/Library/Preferences/PyCharmXX/filetypes Linux ~/.PyCharmXX/config/filetypes %HOMEPATH%\\.PyCharmXX\config\filetypes 2020.1及更高版本 ~/Library/Application Support/JetBrains/PyCharmXX/filetypes Linux ~/.config/JetBrains/PyCharmXX/filetypes %APPDATA%\JetBrains\PyCharmXX\filetypes jenkins 将当前项目的环境变量 作为post的请求中的参数 jenkins中 调用 curl 发送post命令时,使用当前项目的环境变量作为post请求的参数, 要用" ’ ’ "将环境变量括起来。 curl -X POST http://172.26.12.87:9090/send/email -H 'Content-Type: application/json' -H 'cac... 一、在请求头加上 crumb 我现在要使用 webhook 发一个 post 请求给 jenkins,结果报了 403 错误。一个可行的解决方案就是给这个请求头加上 crumb。 在桌面右击空白处点击 git bash, 输入以下命令获取 crumb:curl -u user:password "http://192.168.150.188:8000/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,%22:%22,//crumb)" 上面的 use 自动化PC端部署:1、PC自动化基于:Java +selenium+testng+jenkins 搭建自动化测试环境Selenium 主要完成PC前端页面自动化 2、通过java实现自动化测试代码开发3、通过jenkins完成自动化批量执行4、通过testng实现自动化用例运行结果正确性判断5、通过jenkins完成测试结果输出及测试报告邮件发送 一、测试环境搭建:1.安装JDK2.安装Eclip...     Jenkinsfile是Jenkins2.x版本推出流水线pipeline之后的配置文件,可以将构建过程全部以代码的形式写在Jenkinsfile里面,Jenkinsfile随代码库一起进行维护。关于Jenkinsfile的更多信息请查看Jenkins官网。     流水线是Jenkins2.x版本推出的新特性,按照其字面意思理解,将软件的生产过程与传统工艺的生产过程相比较,从原料... script{ sh(script:"docker images|grep ${project_name}|awk '{print \$3}'|sort -u|xargs docker rmi -f",label:'清理本地docker') }catch(Exception e){ echo 'docker clean failed'. 可以发现预设的变量未能正确读取导致. 后续尝试了重启jenkins服务,重新设置jenkins邮件设置,还原jenkins备份(删除现在的jenkins直接复制历史成功的jenkins备份都不行); 最终尝试出一个解决方案即卸载邮件插件,然后在重新安装.具体的过程如下 1.进入jenkins的插件管理界面 卸载所有的email开 Jenkins无法后台执行命令问题 执行shell是Jenkins来将你填写的shell脚本语句在部署的机器上执行,实际上就是Jenkins启动了子进程到部署的机器上执行命令行,所以**当最后一行命令执行结束后,Jenkins会杀掉所有在此过程中创建的子进程,如果这里有需要后台运行的,或者挂起的任务时,在Jenkins执行结束后,这些挂起的或后台的任务都会被杀掉**,这个问题困扰了我好久,最后整理的几种方案:   先安装插件:set build description   安装该插件后,在【Post-build Actions】栏目中会多出description setter功能,可以实现构建完成后设置当次build的描述信息。这个描述信息不仅会显示在build页面中,同时也会显示在历史构建列表中。   有了这个前提,要将二维码图片展示在历史构建列表中貌似... 今天突然被叫去开会,说项目要实现按自动化部署,生成检查报告。因为项目办要统计数据,不合格就要核减绩效。 作为一名刚工作的小白,我就这么被临危受命了。 然后就是为期一天半的学习,调试,从零到完成这项工作,过程中学到很多,就记录下来。 由于我的邮箱问题之前 被同事占用了,导致我不能提交代码。 这次配置jenkins也是我第一次正式使用git提交代码。 打开git–&gt;修改git仓库中的代码–&gt......