Search code examples
jenkins-pipelinejenkins-groovyjenkins-email-ext

Jenkins Pipeline emailext: How to access build object in pre-send script


I'm using Jenkins ver. 2.150.1 and have some freestyle jobs and some pipeline jobs. In both job types I am using the emailext plugin, with template and pre-send scripts.

It seems that the build variable, which is available in the freestyle projects, is null in the pipeline projects.

The pre-send script is the following (just an example, my script is more complex):

msg.setSubject(msg.getSubject() + " [" + build.getUrl() + "]")

There is no problem with the msg variable. In the freestyle job, this script adds the build url to the mail subject. In the pipeline job, the following is given in the job console:

java.lang.NullPointerException: Cannot invoke method getUrl() on null object

The invocation of emailext in the pipeline job is:

emailext body: '${SCRIPT, template="groovy-html.custom.pipeline.sandbox.template"}', 
         presendScript: '${SCRIPT, template="presend.sandbox.groovy"}', 
         subject: '$DEFAULT_SUBJECT', 
         to: 'user@domain.com'

I would rather find a general solution to this problem (i.e. Access the build variable in a pipeline pre-send script), but would also appreciate any workarounds to my current needs: Access job name, job number, and workspace folder in a pipeline pre-send script.


Solution

  • I have finally found the answer -

    Apparently for presend script in pipeline jobs, the build object does not exist, and instead the run object does. At the time I posted this question this was still undocumented!

    Found the answer in this thread

    Which got the author to update the description in the wiki:

    • run - the build this message belongs to (may be used with FreeStyle or Pipeline jobs)
    • build - the build this message belongs to (only use with FreeStyle jobs)