如何在jenkinsfile中指定何时分支NOT(分支名称)?

时间:2017-04-24 01:41:05

标签: jenkins groovy continuous-integration jenkins-pipeline

如何在Jenkins文件中指定类似以下的内容?

当分支不是x

我知道如何指定分支特定的任务,如:

stage('Master Branch Tasks') {
        when {
            branch "master"
        }
        steps {
          sh '''#!/bin/bash -l
          Do some stuff here
          '''
        }
}

但是,我想指定分支不是主分区或分段的阶段,如下所示:

stage('Example') {
    if (env.BRANCH_NAME != 'master' && env.BRANCH_NAME != 'staging') {
        echo 'This is not master or staging'
    } else {
        echo 'things and stuff'
    }
}

但是上述方法不起作用,但失败并出现以下错误:

WorkflowScript: 62: Not a valid stage section definition: "if 

WorkflowScript: 62: Nothing to execute within stage "Example" 

注意我尝试失败的来源:https://jenkins.io/doc/book/pipeline/syntax/#flow-control

3 个答案:

答案 0 :(得分:28)

解决此issue后,您现在可以执行此操作:

stage('Example (Not master)') {
   when {
       not {
           branch 'master'
       }
   }
   steps {
     sh 'do-non-master.sh'
   }
}

答案 1 :(得分:15)

您还可以使用anyOf指定多个条件(在这种情况下为分支名称):

stage('Example (Not master nor staging)') {
   when {
       not {
          anyOf {
            branch 'master';
            branch 'staging'
          }
       }
   }
   steps {
     sh 'do-non-master-nor-staging.sh'
   }
}

在这种情况下,do-non-master-nor-staging.sh将在 master staging 上的所有分支上运行。

您可以阅读有关内置条件和常规管道语法here的信息。

答案 2 :(得分:10)

帖子中的链接显示了脚本管道语法的示例。您的代码使用声明性管道语法。要在声明中使用脚本化管道,可以使用脚本步骤。

stage('Example') {
    steps {
        script { 
            if (env.BRANCH_NAME != 'master' && env.BRANCH_NAME != 'staging') {
                echo 'This is not master or staging'
            } else {
                echo 'things and stuff'
            }
        }
    }
}