Manish Verma Manish Verma - 1 month ago 20
Groovy Question

How to get default value from groovy script variable in jenkins pipeline job

So the problem is, I am not able to get the default value for controllerIP variable using the getControllerIP method without calling setControllerIP. I tried similar groovy code locally and it works, but not working on my jenkins server. Also tried lots of other combination in my groovy script but nothing worked.
Note that we are using Jenkins: pipeline shared groovy libraries plugin.

This is my pipeline job on Jenkins:

node{

def controllerParameters = new com.company.project.controller.DeploymentParameters() as Object

controllerParameters.setOSUsername('jenkins')
controllerParameters.setOSPassword('jenkins123')
controllerParameters.setBuildNumber(33)
//controllerParameters.setControllerIP('192.44.44.44')
//if I uncomment above line everything works fine but I need to get default value in a case

echo "I want the default value from other file"
controllerParameters.getControllerIP()
echo "my code hangs on above line"

}


This is my other file ../controller/DeploymentParameters.groovy

package com.company.project.controller
import groovy.transform.Field

def String osUsername
def String osPassword
@Field String controllerIP = "NotCreated" //tried few combinations

//Open Stack username
def String setOSUsername(String osUsername) {
this.osUsername = osUsername
}
def String getOSUsername() {
return this.osUsername
}
//Open Stack password
void setOSPassword(String osPassword) {
this.osPassword = osPassword
}
def String getOSPassword() {
return this.osPassword
}

//Open Stack floating ip of master vm
void setControllerIP(String controllerIP) {
this.controllerIP = controllerIP
}

def String getControllerIP() {
return this.controllerIP
}

Answer

When groovy executes lines like this.osUsername = osUsername or return this.osUsername it actually calls getters and setters instead of direct field access.

So this:

def String getOSPassword() {
    return this.osPassword
}

behaves like this:

def String getOSPassword() {
    return this.getOsPassword()
}

And you code enters infinite recursion (same for setter and assignment).

Within your setters and getters you need to use Groovy direct field access operator

def String getOSPassword() {
    return this.@osPassword
}