Conditional step/stage in Jenkins pipeline

微笑、不失礼 提交于 2019-12-03 02:59:15

问题


How do you run a build step/stage only if building a specific branch?

For example, run a deployment step only if the branch is called deployment, leaving everything else the same.


回答1:


Doing the same in declarative pipeline syntax, below are few examples:

stage('master-branch-stuff'){
  agent any
  when{
    branch 'master'
  }
  steps {
    echo 'run this stage - ony if the branch = master branch'
  }
}

stage('feature-branch-stuff') {
    agent label:'test-node'
    when { branch "feature/*" }
    steps {
        echo 'run this stage - only if the branch name started with feature/'
    }
}

stage('expression-branch') {
    agent label:'some-node'
    when {
    expression {
        return env.BRANCH_NAME != 'master';
        }
    }
    steps {
        echo 'run this stage - when branch is not equal to master'
    }
}

stage('env-specific-stuff') {
    agent label:'test-node'
    when { 
      environment name: 'NAME', value: 'this' 
    }
    steps {
        echo 'run this stage - only if the env name and value matches'
    }
}

More effective ways coming up - https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at - https://jenkins.io/doc/book/pipeline/syntax/#when


UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative

equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.

changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.

buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.

tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.




回答2:


Just use if and env.BRANCH_NAME, example:

    if (env.BRANCH_NAME == "deployment") {                                          
        ... do some build ...
    } else {                                   
        ... do something else ...
    }                                                                       


来源:https://stackoverflow.com/questions/37690920/conditional-step-stage-in-jenkins-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!