user1789357
user1789357

Reputation: 93

how to run vars/script.groovy from a Jenkins shared library

I'm trying to get information from a groovy script located under vars called from a shared library Jenkins class but gets an error. some info:

file structure

.
├── src
│   └── org
│       └── jenkins
│            └──shared_library.groovy 
│── vars
│      └── globals.groovy
│
│── jenkinsfile.groovy

vars/globals.groovy

def my_global() {
return 'my_global_name'
}

shared_library class

package src.org.jenkins

class shared_library implements Serializable {
private steps

shared_library(steps) {
    this.steps = steps
}

def some_func(){
  println globals.my_global
}

jenkinsfile

@Library 'shared_library'
import org.jenkins.shared_library

my_shared_library = new shared_library(steps)

node(){
  stage('my_first_stage'){
    println globals.my_global
  }
  stage('my_second_stage'){
    println shared_library.some_func()
  }
}

so, I can see the value for the first print in pipeline, but for the second I get:

No such property: globals for class: src.org.jenkins.shared_library

Upvotes: 1

Views: 5541

Answers (2)

Joerg S
Joerg S

Reputation: 5129

You need to use the steps object as well to access the globals:

def some_func(){
    println steps.globals.my_global()
}

Taking your example that would become

shared_library class

package src.org.jenkins

class shared_library implements Serializable {
private steps

shared_library(steps) {
    this.steps = steps
}

def some_func(){
  println steps.globals.my_global()
}

Edit: Just saw your Jenkinsfile has a typo as well. Need to use the shared library object instead of the class in 'my_second_stage':

Jenkinsfile

@Library('shared_library')
import org.jenkins.shared_library

my_shared_library = new shared_library(steps)

node(){
  stage('my_first_stage'){
    println globals.my_global()
  }
  stage('my_second_stage'){
    println my_shared_library.some_func()
  }
}

Upvotes: 1

Samy
Samy

Reputation: 632

If you are comfortable with defining the value in .properties or .json files you can use 'resource' folder

sharedlibrary/resource/global.properties

In your pipeline script or var/script.groovy

Use the libraryResource method

globalPropertyContent = libraryResource 'global.properties'

access the property values like:

globalPropertyContent.PROJECT_NAME

Upvotes: 0

Related Questions