Jenkins 管道和条件阶段

Jenkins pipeline and conditional stages

我想在所有阶段添加条件:

pipeline {
    agent { label 'unix' }
    options {
        buildDiscarder(logRotator(numToKeepStr: '5', artifactNumToKeepStr: '5'))
    }
    when {branch 'master' }
    stages {
   
    }
}

我找到了在每个 steps 上添加 when 的任何解决方法,但我正在寻找只有一个 when

的解决方案
stage('master-branch-stuff') {
    when {
        branch 'master'
    }
    steps {
        echo 'run this stage - ony if the branch = master branch'
    }
}

如果你想使用纯声明管道,不。

根据他们的文档,https://www.jenkins.io/doc/book/pipeline/syntax/#whenwhen 仅允许“在阶段指令内”。

stage {
  when { ... }
  ...
}

但是,您可以在 script 块中添加阶段。所以你可以做类似

的事情
stage {
  when { ... }
  steps {
    script {
        stage("scripted stage 1") { ... }
        stage("scripted stage 2") { ... }
    }
  }
}

请记住,script 中的所有内容(包括阶段)都将遵循 scripted pipeline 规则

可以这样做

声明式管道

pipeline {
    agent any;
    stages {
        stage('build') {
            when { branch 'master' }
            stages {
                stage('compile') {
                    steps {
                        echo 'compile'
                    }
                }
                stage('test') {
                    steps {
                        echo 'test'
                    }
                }
                stage('package') {
                    steps {
                        echo 'package'
                    }
                }
            }
        }
    }
}

脚本管道

def branch
node {
    stage('checkout') {
        def myScm = checkout scm
        branch = myScm['branch']
    }
    if(branch == 'master') {
      stage('compile') {
          echo "Compile"
      }
      stage('test') {
          echo "Test"
      }
      stage('package') {
          echo "Package"
      }
    } else {
        echo "don't do anything"
    }
}