Amir
Amir

Reputation: 151

Defining FOLDER level variables in Jenkins using a shared \vars library

So I'm trying to make define folder level variables by putting them in a groovy file in the \vars directory.

Alas, the documentation is so bad, that it's impossible to figure out how to do that... Assuming we have to globals G1 and G2, is this how we define them in the groovy file?

#!Groovy

static string G1 = "G1"
static string G2 = "G2"

Assuming the Groovy file is called XYZ.Groovy, how do I define it in the folder so its available for the folder's script?

Assuming I get over that, and that that LIBXYZ is the name the folder associates with the stuff in the /vars directory, is it correct to assume that when I call

@Library("LIBXYZ") _

it will make XYZ available?

In that case, is XYZ.G1 the way to access the globals?

thanks, a.

Upvotes: 4

Views: 4072

Answers (1)

Michael Easter
Michael Easter

Reputation: 24468

I have a working example here as I was recently curious about this. I agree that the documentation is wretched.

The following is similar to the info in README.md.

Prep: note that folder here refers to Jenkins Folders from the CloudBees Folder plugin. It is a way to organize jobs.

Code Layout

The first part to note is src/net/codetojoy/shared/Bar.groovy :

package net.codetojoy.shared

class Bar {
    static def G1 = "G1"
    static def G2 = "G2"

    def id

    def emitLog() { 
        println "TRACER hello from Bar. id: ${id}"
    }
}

The second part is vars/folderFoo.groovy:

def emitLog(message) {
    println "TRACER folderFoo. message: ${message}"
    def bar = new net.codetojoy.shared.Bar(id: 5150)
    bar.emitLog()

    println "TRACER test : " + net.codetojoy.shared.Bar.G1
}

Edit: To use a static/"global" variable in the vars folder, consider the following vars/Keys.groovy:

class Keys {
    static def MY_GLOBAL_VAR3 = "beethoven"
}

The folderFoo.groovy script can use Keys.MY_GLOBAL_VAR3.

And then usage (in my example: Basic.Folder.Jenkinsfile):

@Library('folderFoo') _ 

stage "use shared library"
node {
    script {
        folderFoo.emitLog 'pipeline test!'
    }
}

Jenkins Setup: Folder

  • Go to New Item and create a new Folder
  • configure the folder with a new Pipeline library:
    • Name is folderFoo
    • Default version is master
    • Retrieval Method is Modern SCM
    • Source Code Management in my example is this repo

Jenkins Setup: Pipeline Job

  • create a new Pipeline job in the folder created above
  • though a bit confusing (and self-referential), I create a pipeline job that uses this same this repo
  • specify the Jenkinsfile Basic.Folder.Jenkinsfile
  • the job should run and use the library

Upvotes: 3

Related Questions