How to Set Environment Variables in Jenkins? – 如何在Jenkins中设置环境变量?

最后修改: 2020年 5月 5日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we’ll show the different ways to set and use environment variables in Jenkins.

在本教程中,我们将展示在Jenkins中设置和使用环境变量的不同方法。

To learn more about Jenkins and Pipelines, refer to our intro to Jenkins.

要了解有关Jenkins和管道的更多信息,请参考我们的 Jenkins简介

2. Global Properties

2.全球属性

We can set global properties by navigating to “Manage Jenkins -> Configure System -> Global properties option”.

我们可以通过导航到 “管理Jenkins -> 配置系统 -> 全局属性选项 “来设置全局属性。

Let’s first check the “Environment variables” checkbox and then add the variables and their respective values inside the “List of Variables” section:

让我们首先勾选 “环境变量 “复选框,然后在 “变量列表 “部分添加变量和它们各自的值。

This is one of the easiest and least intrusive ways to set environment variables.

这是设置环境变量的最简单和最不具干扰性的方法之一。

3. Jenkinsfile

3.Jenkinsfile

We can set environment variables globally by declaring them in the environment directive of our Jenkinsfile.

我们可以通过在我们的Jenkinsfileenvironment>指令中声明这些环境变量来全局设置环境变量。

Let’s see how to set two variables, DISABLE_AUTH and DB_ENGINE:

让我们看看如何设置两个变量,DISABLE_AUTHDB_ENGINE

Jenkinsfile (Declarative Pipeline)
pipeline {
    //Setting the environment variables DISABLE_AUTH and DB_ENGINE
    environment {
        DISABLE_AUTH = 'true'
        DB_ENGINE    = 'mysql'
    }

}

This approach of defining the variables in the Jenkins file is useful for instructing the scripts; for example, a Make file.

这种在Jenkins文件中定义变量的方法对指示脚本很有用;例如,一个Make文件。

4. EnvInject

4.EnvInject

We can install and use the EnvInject plugin to inject environment variables during the build startup.

我们可以安装并使用EnvInject插件来在构建启动期间注入环境变量。

In the build configuration window, we select the “Inject environment variables” option in the “Add build step” combo box.

在构建配置窗口,我们在 “添加构建步骤 “组合框中选择 “注入环境变量 “选项。

We can then add the required environment variables in the properties content text box.

然后我们可以在属性内容文本框中添加所需的环境变量。

For example, we can specify the user profile:

例如,我们可以指定用户配置文件。

5. Usage

5.使用方法

Now, we can use any of our environment variables by surrounding the name in ${}:

现在,我们可以通过用${}包围名称来使用我们的任何环境变量。

echo "Database engine is ${DB_ENGINE}"

6. Conclusion

6.结语

In this article, we saw how to set and use environment variables in Jenkins.

在这篇文章中,我们看到了如何在Jenkins中设置和使用环境变量。