如何使用jenkins Declarative Pipeline添加条件postbuild操作?

时间:2018-03-22 09:57:03

标签: jenkins jenkins-pipeline post-build-event

我需要在作业触发postbuild操作之前检查一个条件

我可以看到管道中的帖子部分支持始终,更改,失败,成功,不稳定和中止。作为后期建设条件。但我想检查后期构建操作中的另一个条件。我尝试使用{},但在后期构建操作中不支持。

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                sh 'mvn --version'
            }
        }
    }
    post { 
    }
}

2 个答案:

答案 0 :(得分:1)

您可以在帖子构建操作中添加脚本标记,并可以使用if()来检查您的条件

post {
 failure {
     script{
       if( expression ){
          //Post build action which satisfy the condition  
      } 
    }
  }
}

您还可以在管道中为阶段添加帖子构建操作。在这种情况下,您可以在

中指定条件
pipeline {
stages {
    stage('Example') {
        when {
            //condition that you want check
        }
        steps {
        }
        post { //post build action for the stage
            failure { 
            //post build action that you want to check
            }
        }
    }
}}

答案 1 :(得分:0)

正如你所说。帖子部分中没有when选项。要创建条件,您可以在post部分中创建脚本块,如下例所示:

pipeline {
    agent { node { label 'xxx' } }

    environment {
        STAGE='PRD'
    }

    options {
        buildDiscarder(logRotator(numToKeepStr: '3', artifactNumToKeepStr: '1'))
    }

    stages {
        stage('test') {
            steps {
                sh 'echo "hello world"'
            }
        }
    }

    post {
        always {
            script {
                if (env.STAGE == 'PRD') {
                    echo 'PRD ENVIRONMENT..'
                } else {
                    echo 'OTHER ENVIRONMENT'
                }
            }
        }
    }
}

当STAGE的env var为PRD时,它会在帖子部分打印PRD ENVIRONMENT。如果不是,则会打印:DIFFERENT ENVIRONMENT

使用STAGE='PRD'

运行
[Pipeline] sh
[test] Running shell script
+ echo 'hello world'
hello world
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
PRD ENVIRONMENT..

STAGE='UAT'处运行(当然可以使用参数而不是env变量):

[Pipeline] sh
[test] Running shell script
+ echo 'hello world'
hello world
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
OTHER ENVIRONMENT
[Pipeline] }
[Pipeline] // script