4

We have a Jenkins pipeline setup using the Jenkinsfile to define what needs to be done for the different builds.

In a lot of our stages, we have some work that needs to be done when we're going to be doing a release, but can be skipped if a release isn't going to be done.

Currently we have this code:

when {
  allOf {
    anyOf {
      branch 'master';
      branch 'develop';
    }
    expression {
      return params.DBTESTS
    }
  }
}

repeated across all of the stages that can be skipped.

How would I convert that into a function, so that the logic is in one place similar to something like this:

def isReleasePlanned() {
   return  allOf {
      anyOf {
         branch 'master';
         branch 'develop';
      }
      expression {
        return params.DBTESTS
      }
    }
  }
}

and then used like this:

when {
  isReleasePlanned()
}

In each of the stages. Currently that is a syntax error when Jenkins tries to read the Jenkinsfile.

Sir l33tname
  • 4,026
  • 6
  • 38
  • 49
Danack
  • 24,939
  • 16
  • 90
  • 122

1 Answers1

3

You could try something like

def isReleasePlanned(branch, params){
    return branch ==~ "master|develop" && params.DBTESTS
}

pipeline {
...
   stages {
   ...
       stage("For release"){
           when {
               expression{ isReleasePlanned(GIT_BRANCH, params) }
           }
       }
   }
...
}

Or export the function from a custom library.

Baptiste Beauvais
  • 1,886
  • 1
  • 12
  • 19