Reputation: 101
I am trying to implement my first shared library and I am thinking of the following structure:
src:
shared-library
├─ src
└── Functions1.groovy
└── Functions2.groovy
└─ vars
└── Shared_pipeline.groovy
└── globalVars.groovy
Functions1 and Functions2 will be some classes with some functions that I will use
Share_pipeline would be some sort of "template" that I will use for multiple jobs.
globalVars I want to use it as a place to store common variables that I intend to use in all three groovy files and in the jenkins pipeline aswell.
I have everything figured out except the globalVars.
One ideea that I have is to make globalVars as a class and then I can pass and return an instance of that class throughout my code but I would like as much as possible to avoid this pass-return.
Is there any other way that will allow me to define my "global" variables so I could just use (read and write) them anywhere without having to create an instance of a class and pass that instance arround?
Upvotes: 0
Views: 28
Reputation: 6824
The idea having the global variables defined in a class is the correct approach, as defining it in a groovy file under the vars
folder will make it inaccessible to other classes that are implemented in the src
folder.
To avoid the need for creating instances of this class and passing them around you can use define a class that will be a container for public static variables, this wat they will be available in all folders without the need to initialize the class at any point.
For example you can define something like the following:
package com.global
class Variables implements Serializable {
public static Map MyMap= [:];
public static String MyString = "Some String";
public static Boolean MyBoolean= true;
}
You can then import this class in any file under the src
or vars
folders and use the parameters directly without passing or initializing the class.
For example in a test.groovy file that resides in the vars
folder:
import com.global.Variables
def call(Map params) {
// Access the global variables from the Variables class
if (Variables.MyBoolean) {
println(Variables.MyString)
}
// You can also modify these parameters as they are static and public
Variables.MyMap["key"] = "value"
...
}
You can of course add getters or setters to the global static variables in order to protect the data - but make them static as well so you can avoid the need for the initialization.
Small bonus - you can use the same method described above to access these global parameters directly from a pipeline that loaded this library.
Upvotes: 0