1

I am building a declarative JenkinsFile, I have some common variables that I want to be shared across some Jenkins projects and jobs. So I created a jenkins shared library, but for some reason i can't get my Jenkins file to to read the common environment variables from common groovy.

pipeline {
   environment {
      commonEnv()
      Email_Notification_Enabled="true"
      Slack_Notification_Enabled="false"
   }
}

and in my groovy i had:

def call() {
    a = "abc"
    b = "abc"
}

It throws error that commonEnv() is not allowed in environments. What is the possible way to achieve such behaviour.

Mo Adel
  • 1,136
  • 1
  • 16
  • 29

2 Answers2

1

Since you need to have environment variables that are shared across all Jenkins projects and jobs, you should set them up on Jenkins instance level rather than on a Jenkins project or job level.

So, instead of doing it in a Jenkinsfile (which will do it at Jenkins job level), I will do it in Manage Jenkins > Configure System > Global properties > Environment Variables:

Jenkins
The environment variables could then be read in the pipeline script from Jenkins Global Variable env:

echo "This is my Jenkins global environment variable ${env.MY_ENV_VAR_NAME}"
Sanjeev Sachdev
  • 1,241
  • 1
  • 15
  • 23
  • 1
    Our Jenkins contain thousand of jobs for over 1000 repo, so setting it on a Jenkins level might affect other already defined jobs for other projects. – Mo Adel Jan 02 '19 at 11:55
  • 1
    Earlier your question said "all Jenkins projects" and for that I provided this answer. Now that it says "some Jenkins projects", please see my second answer. Cheers ! – Sanjeev Sachdev Jan 07 '19 at 16:34
1

You could write a Groovy method that sets the common environment variables. Please refer this Stack Overflow question to know how to do this. Include that method in Jenkins pipeline shared library.

Now call this Groovy method in declarative pipeline of each of your jobs. Remember that in a declarative pipeline, you may use Groovy only inside the script step. So, your pipeline would look something like:

    pipeline {    
        stages {    
            stage("First stage") {      
                steps {
                    script {
                        // call to Groovy method that sets environment variables
                    }                        
                    // other steps
                }
             }
             // other stages
        }
    }

Hope, it helps.

Sanjeev Sachdev
  • 1,241
  • 1
  • 15
  • 23