Manish Verma Manish Verma - 1 year ago 234
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:


def controllerParameters = new as Object

//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"
echo "my code hangs on above line"


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

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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download