Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access environment variables in jenkins shared library code

When I use my new shared library I cannot access environment variables for any src class which is executed either directly by the Jenkinsfile or via a var/*.groovy script. This problem persists even when I add withEnv to the var/*groovy script.

What is the trick to get environment variables to propagate to jenkins shared library src class execution?

Jenkinsfile

withEnv(["FOO=BAR2"]) {
  println "Jenkinsfile FOO=${FOO}"
  library 'my-shared-jenkins-library'
  lib.displayEnv()

Shared Library var/lib.groovy

def displayEnv() {
  println "Shared lib var/lib FOO=${FOO}"
  MyClass c = new MyClass()
}

Shared Library src/MyClass.groovy

class MyClass() {
  MyClass() {
    throw new Exception("Shared lib src/MyClass  FOO=${System.getenv('FOO')")
  }
}

** Run Result **

Jenkinsfile FOO=BAR
Shared lib var/lib FOO=BAR
java.lang.Exception: Shared lib src/MyClass FOO=null
...
like image 784
Peter Kahn Avatar asked Jan 12 '18 22:01

Peter Kahn


People also ask

How do you pass an environment variable in Jenkins pipeline?

Like if I need to inject a value within Steps/Script section, in Jenkins pipeline, I can define globally in the environment variables or using Jenkins project Configure General Check mark Prepare an environment for the run Check mark Keep Jenkins environment variables I can provide the environment variable in the ...

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.


2 Answers

It sure looks like the only way to handle this is to pass the this from Jenkins file down to the var/lib.groovy and harvest from that object

Jenkinsfile

withEnv(["FOO=BAR2"]) {
  library 'my-shared-jenkins-library'
  lib.displayEnv(this)

var/lib.groovy

def displayEnv(script) {
 println "Shared lib var/lib FOO=${FOO}"
 MyClass c = new MyClass(script)

}

src class

MyClass(def script) {
  throw new Exception("FOO=${script.env.FOO}")
}
like image 140
Peter Kahn Avatar answered Oct 10 '22 19:10

Peter Kahn


I believe you can populate the environment variable as below, where shared library can access.

Jenkisfile

env.FOO="BAR2"
library 'my-shared-jenkins-library'
lib()

vars/lib.groovy

def call(){
    echo ("FOO: ${FOO}")
    echo ("FOO:"+env.FOO)
}
like image 4
Dillip Kumar Behera Avatar answered Oct 10 '22 18:10

Dillip Kumar Behera