3

My question is similar to this one about how to load an external groovy script, and then calling a method from it in a different groovy script. So far I have been able to get methods that don't return a value to work but I am having trouble getting a returned value into a variable that is called.

For example, the following pipeline code works but gives a value of null for $build_user when I run the Jenkins pipeline. It doesn't actually return what I expect it to and I don't know why.

node { stage('test') { def tools = load "/var/lib/jenkins/workflow-libs/vars/tools.groovy" build_user = tools.get_user() echo "build_user: $build_user" } } 

Here is what the relevant tools.groovy looks like.

def exampleMethod() { // Do stuff } // Try to get a build username def get_user() { try { wrap([$class: 'BuildUser']) { // Set up our variables fallback_user = 'GitHub' github_user = BUILD_USER commit_author = 'Test1' // Try to use Jenkins build user first if (github_user) { echo "using github_user: $github_user" return github_user } // Otherwise try to use commit author else if (commit_author) { echo "using commit_author: $commit_author" return commit_author } // Otherwise username is blank so we use the default fallback else { echo "using fallback: $fallback_user" return fallback_user } } } catch (err) { // Ignore errors } echo "Done." } return this 

Here is the full Jenkins output for the above code.

Started by user XXX [Pipeline] node Running on master in /var/lib/jenkins/workspace/test [Pipeline] { [Pipeline] stage [Pipeline] { (test) [Pipeline] load [Pipeline] { (/var/lib/jenkins/workflow-libs/vars/tools.groovy) [Pipeline] } [Pipeline] // load [Pipeline] wrap [Pipeline] { [Pipeline] echo using github_user: XXX [Pipeline] } [Pipeline] // wrap [Pipeline] echo Done. [Pipeline] echo build_user: null [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline Finished: SUCCESS 

The above method doesn't work at all if I remove return this at the end and throws the following error in Jenkins.

java.lang.NullPointerException: Cannot invoke method get_user() on null object ...

What am I doing wrong? I suspect that I'm missing something easy but I'm not great with Groovy, so I'm not sure what it could be.

2 Answers 2

8

You have to end your tools.groovywith return this.
See the answer on this question How do you load a groovy file and execute it

Sign up to request clarification or add additional context in comments.

Comments

1

your function get_user() returns nothing.

the return(s) inside wrap([$class: 'BuildUser']) {...} do return from wrap class and not from your function.

1 Comment

That was it. Instead of returning inside I just assigned to a variable and returned after the wrap.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.