Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Pipeline build step - getBuildVariables() returns empty map

I have the following code in a test Jenkinsfile:

node {
    stage 'Build'
    def job1 = build 'Sample_Freestyle'

    def dur = job1.getDuration()
    println dur

    def vars = job1.getBuildVariables()
    println vars

    def myMap = [k1:'v1', k2:'v2', k3:'v3']
    println myMap
}

As I understand it, when I use the build step a RunWrapper object is returned. I am trying to get the build variables of my test job named "Sample_Freestyle", which at them moment runs a simple Windows batch command:

echo "Hello World"

Whenever I run this, it executes correctly, however I'm left with an empty map. I tested the getDuration() method and that returns as expected. I took a look at the RunWrapper class here and it may be that env is null (circa line 212), but that's only a hypothesis.

Does anyone know why I would be getting an empty map when calling getBuildVariables()? Am I going about this in the wrong way?

like image 461
Joseph Pratt Avatar asked Aug 30 '17 21:08

Joseph Pratt


2 Answers

In case anyone was searching for a solution in declarative pipelines. I wanted to grab downstream job env variable (multibranch declaritive pipeline) My downstream job sets an environment variable as part of it's build.

So it my upstream I do this:

//downstream job kickoff
def buildResult = build job: "<downstreamjob>"
//downstream sets a new env variable env.PACKAGE_NAME
def packageName = buildResult.buildVariables.PACKAGE_NAME
like image 75
hctahkram Avatar answered Nov 11 '22 01:11

hctahkram


getBuildVariables() returns the job's user-defined parameters, not the job's environment variables such as WORKSPACE or BUILD_TAG.

Based on Vitalii's comment, I did an experiment and added a parameter to the Sample_Freestyle job. When I added a test string parameter the map was no longer empty! I got:

{TEST_PARAMETER=Test Parameter}

I suggest the method name be changed from getBuildVariables() to getJobParameters() or getBuildParameters() for consistent naming.

like image 44
Joseph Pratt Avatar answered Nov 11 '22 00:11

Joseph Pratt