Search code examples
windowsgroovyjenkinsenvironment-variables

Access to build environment variables from a groovy script in a Jenkins build step (Windows)


I'm using Scriptler plugin, so I can run a groovy script as a build step. My Jenkins slaves are running on windows in service mode. With scriptler, I don't need to use windows batch scripts.

But I have trouble to get the environment variables in a build step... This is working:

System.getenv("BASE")

Where BASE is part of the env-vars on jenkins startup. However, I would like to get

%JOB_NAME%

If I'm adding an "Execute Windows batch command" build step:

echo %JOB_NAME%

It works. If I'm adding a scriptler script as a build step with the same settings:

println "JOB_NAME: " + System.getenv("JOB_NAME")

I'm getting:

JOB_NAME: null

So how can I reach the injected environment variables from a groovy script as a build step?


Solution

  • The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:

    1. When you add the Scriptler build step into your job, select the option "Define script parameters"

    2. Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.

    3. In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:

      println "JOB_NAME = $JOB_NAME"

    I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!