How to get values of env vars by writing groovy script on jenkins script console?

Viewed 2110

I searched a lot for this problem but couldn't find working solution anywhere. Can anybody please help me out? I want to get already existing env vars value through jenkins script console.

2 Answers

You need to distinguish:

If you see

 groovy.lang.MissingPropertyException: No such property: manager for class: Script1

Check this answer, and define build first:

import hudson.model.*

def build = Thread.currentThread().executable
def buildNumber = build.number

According to this answer, in order to access env vars from Jenkins script console, do as follows :

import jenkins.model.*;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.EnvVars;

jenkins = Jenkins.instance;
EnvironmentVariablesNodeProperty prop = jenkins.getGlobalNodeProperties().get(EnvironmentVariablesNodeProperty.class)
EnvVars env = prop.getEnvVars()

def myVariable = env['MY_VAR']

The env vars listed in http://<JENKINS_URL>/env-vars.html are available for each build. In order to access these variables in the Jenkins script console you need to define first the build :

build = Jenkins.instance.getItemByFullName('JOB_NAME').getBuildByNumber(BUILD_NUMBER)
envvars = build.getEnvironment()
envvars.each{envvar ->
  println envvar
}
Related