Problem defining global variables

39 views
Skip to first unread message

Sverre Moe

unread,
Dec 15, 2016, 5:11:35 AM12/15/16
to Jenkins Users

#vars/variables.groovy
def setFoo(f) {
 
this.foo = f
}

def isFoo() {
 
return this.foo
}

#src/com/company/ci/Build.groovy
void execute() {
 
def foo = false
 
if (env.BRANCH_NAME.equals("master")) {
    foo
= true
 
}
  variables
.setFoo(foo)
}

#Jenkinsfile
def build = new com.company.ci.Build()
build
.execute()

def foo = variables.isFoo()
if (foo) {
   println "We got foo"
}

groovy.lang.MissingPropertyException: No such property: foo for class: variables
Possible solutions: foo

If I use variables.foo or if I change isFoo() to getFoo() it calls getFoo countless times and hangs.

I am not sure what I am doing wrong here. Any clues?
I have no problem accessing variables.getFoo() within Build.groovy, but not in the Jenkinsfile afterwards.

Sverre Moe

unread,
Dec 19, 2016, 6:52:59 AM12/19/16
to Jenkins Users
Is it a problem with scope perhaps?

Tried setting foo first before calling build.execute()
variables.setFoo(true)

def
build = new com.company.ci.Build()
build
.execute()

def foo = variables.isFoo()
if (foo) {
  println "We got foo"
} else{
  println
"No foo"
}

Within build.execute() it sets foo to false, but it does not seem the Jenkinsfile is aware if that. 
Is it creating two instances of variables, one for Build and one for Jenkinsfile?

Sverre Moe

unread,
Jan 6, 2017, 2:32:28 AM1/6/17
to Jenkins Users
Must be a way in Jenkinsfile to access variables set within a Shared Library script.
I could set a return variable for execute(), not a good solutions if I want to access more than one variable.

def build = new com.company.ci.Build()
def foo = build.execute()

Unless I can return the variables object.
def build = new com.company.ci.Build()
def variables = build.execute()
def foo = variables.getFoo()
def bar = variables.getBar()
Reply all
Reply to author
Forward
0 new messages