简体   繁体   English

Jenkins以常规方法共享常见环境变量

[英]Jenkins Share common environment variables in a groovy method

I am building a declarative JenkinsFile, I have some common variables that I want to be shared across some Jenkins projects and jobs. 我正在构建一个声明性的JenkinsFile,我有一些通用变量,希望在某些Jenkins项目和工作中共享。 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. 因此,我创建了一个jenkins共享库,但是由于某些原因,我无法让我的Jenkins文件从通用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. 抛出错误,即环境中不允许commonEnv()。 What is the possible way to achieve such behaviour. 实现这种行为的可能方法是什么?

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. 由于您需要在所有Jenkins项目和作业之间共享环境变量,因此应在Jenkins 实例级别而不是Jenkins 项目工作级别设置它们。

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 : 因此,我将在Manage Jenkins > 配置系统 > 全局属性 > 环境变量中执行此操作,而不是在Jenkinsfile中执行此操作(它将在Jenkins作业级别执行此操作):

詹金斯
The environment variables could then be read in the pipeline script from Jenkins Global Variable env : 然后可以从Jenkins全局变量 env在管道脚本中读取环境变量:

echo "This is my Jenkins global environment variable ${env.MY_ENV_VAR_NAME}"

You could write a Groovy method that sets the common environment variables. 您可以编写一个Groovy方法来设置公共环境变量。 Please refer this Stack Overflow question to know how to do this. 请参阅此堆栈溢出问题以了解如何执行此操作。 Include that method in Jenkins pipeline shared library. 在Jenkins管道共享库中包含该方法。

Now call this Groovy method in declarative pipeline of each of your jobs. 现在,在每个作业的声明性管道中调用此Groovy方法。 Remember that in a declarative pipeline, you may use Groovy only inside the script step. 请记住,在声明性管道中,您只能在script步骤内部使用Groovy。 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. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM