Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Shared Pipeline Library : Can I declare static variables in vars file?

Does Jenkins Shared Pipeline Library supports static variables in vars/*. groovy files?

Examples

Referencing global variables "implicitly" (doesn't work)

file: vars/foo.groovy
---
def functionFoo() {return "foo"}



file: vars/bar.groovy
---
def result = functionFoo()
def functionBar() {println result}


file:Jenkinsfile
---
@Library('MyLib') _
bar.functionBar()

This throws error:

groovy.lang.MissingPropertyException: No such property: result for class: groovy.lang.Binding at groovy.lang.Binding.getVariable(Binding.java:63) at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:224) at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241) at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238) at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:24) at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20) ....

Referencing global variables "explicitly" (does work)

file: vars/foo.groovy
---
def functionFoo() {return "foo"}



file: vars/bar.groovy
---
def functionBar() {
    def result = functionFoo()
    println result
}


file:Jenkinsfile
---
@Library('MyLib') _
bar.functionBar()

Summary

I assume that variables are either initialized in different way or simply cannot be used withing vars/ directory the same way function can. Is this feature part of Groovy language? Or a limitation of Jenkins' Global Pipeline Library?

like image 299
luka5z Avatar asked Oct 24 '16 20:10

luka5z


People also ask

How do you declare a variable in Jenkins pipeline script?

Jenkins pipeline environment variables: You can define your environment variables in both — global and per-stage — simultaneously. Globally defined variables can be used in all stages but stage defined variables can only be used within that stage. Environment variables can be defined using NAME = VALUE syntax.

How does Jenkins shared library work?

A shared library in Jenkins is a collection of Groovy scripts shared between different Jenkins jobs. To run the scripts, they are pulled into a Jenkinsfile. Each shared library requires users to define a name and a method of retrieving source code.

How do you call a shared library in Jenkins?

Create a separate git repo for the Jenkins pipeline library & push the shared library code to that repo. Integrate the shared library repo in Jenkins under the Manage Jenkins section. Create Jenkinsfile in the project. In that Jenkinsfile, Import & use the shared library.


1 Answers

To define a variable inside the groovy vars, rather than a function, use groovy.transform.Field:

@groovy.transform.Field result = functionFoo()
def functionBar() {println this.result}
like image 196
BMitch Avatar answered Oct 19 '22 19:10

BMitch