Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value from a function in Jenkins pipeline for an 'allOf'

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.

like image 962
Danack Avatar asked Oct 16 '25 14:10

Danack


1 Answers

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.

like image 174
Baptiste Beauvais Avatar answered Oct 19 '25 10:10

Baptiste Beauvais