Search code examples
groovyjenkinsjenkins-plugins

Groovy Postbuild do not execute scripts on Jenkins


I've written simple groovy script, but I don't know how to execute it on Jenkins.

Look at this simple script:

String jbN = System.getenv('JOB_NAME')
println  jbN
println "Hello"

I would except that I will reveived at least "Hello". Script give no return. I've just received Build step 'Groovy Postbuild' marked build as failure(or success)

It seems that script is not executed.

EDIT:

I didn't add it, but I have already script which will analize logs, so I need it to execute it post-build. The problem is bigger then I thought. Plugins: "Scriptler" or "Groovy Plugin" do not print anything. Script which I'm trying to print out:

String jbN = System.getenv('JOB_NAME')
println  jbN

Solution

  • I found the solution:

    Script was executed but wasn't printed to console output. To print result to console output you need to write: manager.listener.logger.println("Some string") instead of println.

    To make it shorter do:

    logger = manager.listener.logger.&println // and call like this: logger("test log message")

    EDIT: add in logger example and to describe how to get env vars (and how to not get them) and to hopefully save people some debugging time . . . this is simple but awkward stuff.

    To get the workspace you can go through the manager object. Like this:

    manager.build.workspace

    To get env vars, this does not work:

    String jbN = System.getenv('JOB_NAME')

    It shows jbN is null. That makes sense as JOB_NAME is not an actual system environment var.

    This also does not work to get env vars, an exception is thrown:

    ${manager.envVars['WORKSPACE']}

    This does work to get jenkins job "env vars" like WORKSPACE, JOB_NAME, BUILD_NAME:

    def build = Thread.currentThread().executable workspace = build.getEnvVars()["WORKSPACE"]

    Example of use, you can call a groovy script in workspace like this:

    evaluate(new File(manager.build.workspace.toString() + "/dirinworkspace/scriptname.groovy"))