🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# GitLab CI/CD environment variables > 原文:[https://docs.gitlab.com/ee/ci/variables/README.html](https://docs.gitlab.com/ee/ci/variables/README.html) * [Predefined environment variables](#predefined-environment-variables) * [Use predefined environment variables](#use-predefined-environment-variables) * [Custom environment variables](#custom-environment-variables) * [Create a custom variable in `.gitlab-ci.yml`](#create-a-custom-variable-in-gitlab-ciyml) * [Create a custom variable in the UI](#create-a-custom-variable-in-the-ui) * [Custom environment variables of type Variable](#custom-environment-variables-of-type-variable) * [Custom environment variables of type File](#custom-environment-variables-of-type-file) * [Mask a custom variable](#mask-a-custom-variable) * [Masked variable requirements](#masked-variable-requirements) * [Protect a custom variable](#protect-a-custom-variable) * [Custom variables validated by GitLab](#custom-variables-validated-by-gitlab) * [Syntax of environment variables in job scripts](#syntax-of-environment-variables-in-job-scripts) * [Bash](#bash) * [PowerShell](#powershell) * [Windows Batch](#windows-batch) * [List all environment variables](#list-all-environment-variables) * [`.gitlab-ci.yml` defined variables](#gitlab-ciyml-defined-variables) * [Group-level environment variables](#group-level-environment-variables) * [Instance-level CI/CD environment variables](#instance-level-cicd-environment-variables) * [Enable or disable UI interface for instance-level CI/CD variables](#enable-or-disable-ui-interface-for-instance-level-cicd-variables) * [Inherit environment variables](#inherit-environment-variables) * [Priority of environment variables](#priority-of-environment-variables) * [Unsupported variables](#unsupported-variables) * [Where variables can be used](#where-variables-can-be-used) * [Advanced use](#advanced-use) * [Limit the environment scopes of environment variables](#limit-the-environment-scopes-of-environment-variables) * [Deployment environment variables](#deployment-environment-variables) * [Auto DevOps environment variables](#auto-devops-environment-variables) * [Override a variable by manually running a pipeline](#override-a-variable-by-manually-running-a-pipeline) * [Environment variables expressions](#environment-variables-expressions) * [Syntax of environment variable expressions](#syntax-of-environment-variable-expressions) * [Storing regular expressions in variables](#storing-regular-expressions-in-variables) * [Debug logging](#debug-logging) * [Video walkthrough of a working example](#video-walkthrough-of-a-working-example) # GitLab CI/CD environment variables[](#gitlab-cicd-environment-variables "Permalink") 环境变量是一个动态命名的值,它可以影响正在运行的进程在操作系统上的行为方式. 环境变量是进程在其中运行的环境的一部分. 例如,正在运行的进程可以查询`TEMP`环境变量的值以发现合适的位置来存储临时文件,或者为可以在不同脚本中重用的数据库定义`URL` . 变量对于在 GitLab CI / CD 中自定义作业很有用. 使用变量时,不必对值进行硬编码. > 有关高级使用 GitLab CI / CD 的更多信息: > > * 由 GitLab 工程师共享的这[7 种高级 GitLab CI 工作流程黑客,](https://about.gitlab.com/webcast/7cicd-hacks/)可以更快地提高生产力. > * 了解 Cloud Native Computing Foundation(CNCF)如何通过 GitLab CI / CD [消除](https://about.gitlab.com/customers/cncf/)许多云提供商之间管理项目[的复杂性](https://about.gitlab.com/customers/cncf/) . ## Predefined environment variables[](#predefined-environment-variables "Permalink") GitLab CI / CD 具有一组[默认的预定义变量](predefined_variables.html) ,您可以使用它们而无需任何其他说明. 您可以呼叫问题编号,用户名,分支名称,管道和提交 ID 等. GitLab 为 Runner 的本地环境提供了预定义的环境变量. GitLab 读取`.gitlab-ci.yml`文件,并将信息发送到 Runner,在此处公开变量. 然后,运行程序运行脚本命令. ### Use predefined environment variables[](#use-predefined-environment-variables "Permalink") 您可以选择现有的预定义变量之一,以由 Runner 输出. 本示例说明如何使用预定义变量`CI_JOB_STAGE`输出作业的阶段. 在您的`.gitlab-ci.yml`文件中,从脚本中调用变量. 确保使用正确的[语法](#syntax-of-environment-variables-in-job-scripts) . ``` test_variable: stage: test script: - echo $CI_JOB_STAGE ``` 在这种情况下,跑步者输出工作`test_variable`的`stage` ,即`test` : [![Output `$CI_JOB_STAGE`](https://img.kancloud.cn/04/42/044279c5260f8e17b42ee0a5f500c962_1010x531.png)](img/ci_job_stage_output_example.png) 再举一个例子,假设您使用自己的 GitLab 实例,并且想知道 GitLab 页面在哪个域下提供服务. 您可以通过在脚本中使用预定义变量`$CI_PAGES_DOMAIN`来调用它: ``` pages: script: - ... - echo $CI_PAGES_DOMAIN ``` 对于 GitLab.com 用户,输出将为`gitlab.io` . 对于您的私有实例,输出将是您的系统管理员定义的任何内容. ## Custom environment variables[](#custom-environment-variables "Permalink") 当需要特定的自定义环境变量时,可以[在 UI](#create-a-custom-variable-in-the-ui)中[,API](../../api/project_level_variables.html)中或直接[在`.gitlab-ci.yml`文件中进行设置](#create-a-custom-variable-in-gitlab-ciyml) . 每当管道运行时,Runner 就会使用这些变量. 您还[可以手动覆盖特定管道的变量值](../pipelines/index.html#specifying-variables-when-running-manual-jobs) . 变量有两种类型: **Variable**和**File** . 您无法在`.gitlab-ci.yml`文件中设置类型,但可以在 UI 和 API 中进行设置. ### Create a custom variable in `.gitlab-ci.yml`[](#create-a-custom-variable-in-gitlab-ciyml "Permalink") 要创建自定义`env_var`在可变[`.gitlab-ci.yml`](../yaml/README.html#variables)文件中,定义下的变量/值对`variables` : ``` variables: TEST: "HELLO WORLD" ``` 然后,您可以在脚本中调用其值: ``` script: - echo "$TEST" ``` 有关更多详细信息,请参见[`.gitlab-ci.yml`定义的变量](#gitlab-ciyml-defined-variables) . ### Create a custom variable in the UI[](#create-a-custom-variable-in-the-ui "Permalink") 在用户界面中,您可以添加或更新自定义环境变量: 1. 转到项目的**"设置">" CI / CD",**然后展开" **变量"**部分. 2. 单击**添加变量**按钮. 在" **添加变量**模式"中,填写详细信息: * **密钥** :必须是一行,没有空格,只能使用字母,数字或`_` . * **价值** :无限制. * **Type**: `File` or `Variable`. * **环境范围** : `All`或特定环境. * **保护变量** (可选):如果选中,则该变量将仅在在受保护的分支或标签上运行的管道中可用. * **屏蔽变量** (可选):如果选中,则变量的**值**将在作业日志中被屏蔽. 如果该值不满足[屏蔽要求,](#masked-variable-requirements)则变量将无法保存. 创建变量后,您可以通过点击 **编辑**按钮. 设置变量后,请从`.gitlab-ci.yml`文件中调用它: ``` test_variable: stage: test script: - echo $CI_JOB_STAGE # calls a predefined variable - echo $TEST # calls a custom variable of type `env_var` - echo $GREETING # calls a custom variable of type `file` that contains the path to the temp file - cat $GREETING # the temp file itself contains the variable value ``` 输出将是: [![Output custom variable](https://img.kancloud.cn/9a/ce/9acebfbdd3bdcfb9ab5fa6cef34de401_982x675.png)](img/custom_variables_output.png) ### Custom environment variables of type Variable[](#custom-environment-variables-of-type-variable "Permalink") 在 GitLab 11.11 中[引入](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/46806) . 对于类型为**Variable 的变量** ,Runner 会创建一个环境变量,该环境变量将键用作名称,并将值用作值. 有[一些](#custom-variables-validated-by-gitlab)这种类型的[预定义变量](#custom-variables-validated-by-gitlab) ,可以进一步验证. 它们在您在 UI 中添加或更新变量时出现. ### Custom environment variables of type File[](#custom-environment-variables-of-type-file "Permalink") 在 GitLab 11.11 中[引入](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/46806) . 对于**File**类型的变量,Runner 创建一个环境变量,该环境变量使用键作为名称. 对于该值,Runner 将变量值写入临时文件并使用此路径. 您可以使用诸如[AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html)和[`kubectl`](https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#the-kubeconfig-environment-variable)类[的](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html)工具通过使用**File** type 变量来自定义配置. 过去,常见的模式是读取 CI 变量的值,将其保存在文件中,然后在脚本中使用新创建的文件: ``` # Read certificate stored in $KUBE_CA_PEM variable and save it in a new file echo "$KUBE_CA_PEM" > "$(pwd)/kube.ca.pem" # Pass the newly created file to kubectl kubectl config set-cluster e2e --server="$KUBE_URL" --certificate-authority="$(pwd)/kube.ca.pem" ``` 代替此,您可以使用**文件**类型变量. 例如,如果您具有以下变量: * 类型为**Variable** : `KUBE_URL` **变量** ,其值为`https://example.com` . * 类型为**File** : `KUBE_CA_PEM`变量,其值为证书. 您可以从`.gitlab-ci.yml`调用它们,如下所示: ``` kubectl config set-cluster e2e --server="$KUBE_URL" --certificate-authority="$KUBE_CA_PEM" ``` ### Mask a custom variable[](#mask-a-custom-variable "Permalink") 在 GitLab 11.10 中[引入](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/13784) 可以屏蔽变量,以便将变量的值隐藏在作业日志中. 要屏蔽变量: 1. 转到**设置> CI / CD** . 2. 展开**变量**部分. 3. 在您要保护的变量旁边,点击**编辑** . 4. 选择**掩码变量**复选框. 5. Click **更新变量**. #### Masked variable requirements[](#masked-variable-requirements "Permalink") 变量的值必须: * 在一行中. * 至少要包含 8 个字符. * 不是预定义或自定义环境变量. * 仅由 Base64 字母(RFC4648)中的字符组成. [在 GitLab 12.2](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/63043)和更高版本中, `@`和`:`也是有效值. 您不能屏蔽不满足这些要求的变量. ### Protect a custom variable[](#protect-a-custom-variable "Permalink") 在 GitLab 9.3 中引入. 变量可以被保护. 受保护的变量将安全地传递到仅在[受保护的分支](../../user/project/protected_branches.html)或[受保护的标签](../../user/project/protected_tags.html)上运行的管道. 其他管道不获取受保护的变量. 要保护变量: 1. 转到**设置> CI / CD** . 2. 展开**变量**部分. 3. 在您要保护的变量旁边,点击**编辑** . 4. 选择**保护变量**复选框. 5. Click **更新变量**. 该变量可用于所有后续管道. 受保护的变量只能由拥有[维护者权限的](../../user/permissions.html#project-members-permissions)项目成员更新或查看. ### Custom variables validated by GitLab[](#custom-variables-validated-by-gitlab "Permalink") UI 中列出了一些变量,因此您可以更快地选择它们. GitLab 会验证这些变量的值,以确保它们的格式正确. | Variable | 允许值 | 引入 | | --- | --- | --- | | `AWS_ACCESS_KEY_ID` | 20 个字符:字母,数字 | 12.10 | | `AWS_DEFAULT_REGION` | Any | 12.10 | | `AWS_SECRET_ACCESS_KEY` | 40 个字符:字母,数字,特殊字符 | 12.10 | **注意:**存储凭据时,会涉及安全性. 例如,如果您使用的是 AWS 密钥,请遵循其[最佳做法](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) . ## Syntax of environment variables in job scripts[](#syntax-of-environment-variables-in-job-scripts "Permalink") 所有变量都在构建环境中设置为环境变量,并且可以使用用于访问此类变量的常规方法来访问它们. 在大多数情况下, `bash`或`sh`用于执行作业脚本. 要访问环境变量,请为 Runner's [shell](https://docs.gitlab.com/runner/executors/)使用语法. | Shell | Usage | | --- | --- | | bash/sh | `$variable` | | PowerShell | `$env:variable` (主`$env:variable` )或`$variable` | | Windows 批处理 | `%variable%` | ### Bash[](#bash "Permalink") 要在**bash 中**访问环境变量,请在变量名前加上( `$` ): ``` job_name: script: - echo $CI_JOB_ID ``` ### PowerShell[](#powershell "Permalink") 要访问**Windows PowerShell**环境中的环境变量,请在变量名前加上( `$env:` . 对于由 GitLab CI 设置的环境变量,包括由[`variables`](https://gitlab.com/gitlab-org/gitlab/blob/master/doc/ci/yaml/README.md#variables)参数设置的环境[`variables`](https://gitlab.com/gitlab-org/gitlab/blob/master/doc/ci/yaml/README.md#variables) ,还可以通过在[GitLab Runner 1.0.0 开始](https://gitlab.com/gitlab-org/gitlab-runner/-/commit/abc44bb158008cd3a49c0d8173717c38dadb29ae#47afd7e8f12afdb8f0246262488f24e6dd071a22) ,通过在变量名称前加上( `$` )来访问它们. 但是,必须使用( `$env:`访问系统设置的环境变量. ``` job_name: script: - echo $env:CI_JOB_ID - echo $CI_JOB_ID - echo $env:PATH ``` 在[某些情况下,](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/4115#note_157692820)环境变量可能需要用引号引起来才能正确扩展: ``` job_name: script: - D:\\qislsf\\apache-ant-1.10.5\\bin\\ant.bat "-DsosposDailyUsr=$env:SOSPOS_DAILY_USR" portal_test ``` ### Windows Batch[](#windows-batch "Permalink") 要访问**Windows Batch 中的**环境变量,请用( `%` )包围变量: ``` job_name: script: - echo %CI_JOB_ID% ``` ### List all environment variables[](#list-all-environment-variables "Permalink") 您还可以使用 Bash 中的`export`命令或 PowerShell 中的`dir env:`命令列出所有环境变量. 请注意,这还将在作业日志中公开您设置的所有变量的值: ``` job_name: script: - export # - 'dir env:' # use this for PowerShell ``` 值示例: ``` export CI_JOB_ID="50" export CI_COMMIT_SHA="1ecfd275763eff1d6b4844ea3168962458c9f27a" export CI_COMMIT_SHORT_SHA="1ecfd275" export CI_COMMIT_REF_NAME="master" export CI_REPOSITORY_URL="https://gitlab-ci-token:abcde-1234ABCD5678ef@example.com/gitlab-org/gitlab-foss.git" export CI_COMMIT_TAG="1.0.0" export CI_JOB_NAME="spec:other" export CI_JOB_STAGE="test" export CI_JOB_MANUAL="true" export CI_JOB_TRIGGERED="true" export CI_JOB_TOKEN="abcde-1234ABCD5678ef" export CI_PIPELINE_ID="1000" export CI_PIPELINE_IID="10" export CI_PAGES_DOMAIN="gitlab.io" export CI_PAGES_URL="https://gitlab-org.gitlab.io/gitlab-foss" export CI_PROJECT_ID="34" export CI_PROJECT_DIR="/builds/gitlab-org/gitlab-foss" export CI_PROJECT_NAME="gitlab-foss" export CI_PROJECT_TITLE="GitLab FOSS" export CI_PROJECT_NAMESPACE="gitlab-org" export CI_PROJECT_ROOT_NAMESPACE="gitlab-org" export CI_PROJECT_PATH="gitlab-org/gitlab-foss" export CI_PROJECT_URL="https://example.com/gitlab-org/gitlab-foss" export CI_REGISTRY="registry.example.com" export CI_REGISTRY_IMAGE="registry.example.com/gitlab-org/gitlab-foss" export CI_REGISTRY_USER="gitlab-ci-token" export CI_REGISTRY_PASSWORD="longalfanumstring" export CI_RUNNER_ID="10" export CI_RUNNER_DESCRIPTION="my runner" export CI_RUNNER_TAGS="docker, linux" export CI_SERVER="yes" export CI_SERVER_URL="https://example.com" export CI_SERVER_HOST="example.com" export CI_SERVER_PORT="443" export CI_SERVER_PROTOCOL="https" export CI_SERVER_NAME="GitLab" export CI_SERVER_REVISION="70606bf" export CI_SERVER_VERSION="8.9.0" export CI_SERVER_VERSION_MAJOR="8" export CI_SERVER_VERSION_MINOR="9" export CI_SERVER_VERSION_PATCH="0" export GITLAB_USER_EMAIL="user@example.com" export GITLAB_USER_ID="42" ``` ## `.gitlab-ci.yml` defined variables[](#gitlab-ciyml-defined-variables "Permalink") **注意:**此功能需要 GitLab Runner 0.5.0 或更高版本以及 GitLab 7.14 或更高版本. 您可以将在构建环境中设置的变量添加到`.gitlab-ci.yml` . 这些变量保存在存储库中,它们旨在存储非敏感项目配置,例如`RAILS_ENV`或`DATABASE_URL` . 例如,如果将变量全局设置为下方(而不是在作业内部),它将在所有已执行的命令和脚本中使用: ``` variables: DATABASE_URL: "postgres://postgres@postgres/my_database" ``` 还将 YAML 定义的变量设置为所有创建的[服务容器](../docker/using_docker_images.html) ,以便您可以对其进行微调. 变量可以在全局级别定义,也可以在作业级别定义. 要在作业中关闭全局定义的变量,请定义一个空哈希: ``` job_name: variables: {} ``` 您可以在变量定义内使用其他变量(或使用`$$`对其进行转义): ``` variables: LS_CMD: 'ls $FLAGS $$TMP_DIR' FLAGS: '-al' script: - 'eval $LS_CMD' # will execute 'ls -al $TMP_DIR' ``` ## Group-level environment variables[](#group-level-environment-variables "Permalink") Introduced in GitLab 9.4. 您可以定义在管道环境中设置的每个项目或每个组的变量. 组级变量存储在存储库之外(不在`.gitlab-ci.yml` ),并安全地传递到 GitLab Runner,这使它们在管道运行期间可用. 对于**不**使用外部密钥存储或使用 GitLab [与 HashiCorp Vault 集成的](../examples/authenticating-with-hashicorp-vault/index.html)高级用户,我们建议使用组环境变量来存储密码,SSH 密钥和凭据之类的机密. 组级变量可以通过以下方式添加: 1. 导航到组的**"设置">" CI / CD"**页面. 2. 在" **变量"**部分中输入变量类型,键和值. [子组的](../../user/group/subgroups/index.html)任何变量将被递归继承. 设置它们后,它们将可用于所有后续管道. 可以通过以下方式在项目中查看任何组级用户定义的变量: 1. 导航到项目的**"设置">" CI / CD"**页面. 2. 展开**变量**部分. [![CI/CD settings - inherited variables](https://img.kancloud.cn/63/ee/63eeabd249cae50defebb5e1d4ba2f5b_915x331.png)](img/inherited_group_variables_v12_5.png) ## Instance-level CI/CD environment variables[](#instance-level-cicd-environment-variables "Permalink") 在 GitLab 13.0 中[引入](https://gitlab.com/gitlab-org/gitlab/-/issues/14108) . 实例变量非常有用,因为不再需要为所有项目重复手动输入相同的凭据. 实例级变量可用于实例上的所有项目和组. **注意:**实例级变量的最大数量[计划为 25](https://gitlab.com/gitlab-org/gitlab/-/issues/216097) . 您可以通过 UI 或[API](../../api/instance_level_ci_variables.html)定义实例级变量. 要添加实例级变量: 1. 导航到管理区域的**"设置">" CI / CD",**然后展开" **变量"**部分. 2. 单击**添加变量**按钮,然后填写详细信息: * **密钥** :必须为一行,只能使用字母,数字或`_` (下划线),且不能有空格. * **值** :允许 700 个字符. * **Type**: `File` or `Variable`. * **保护变量** (可选):如果选中,则该变量将仅在在受保护的分支或标签上运行的管道中可用. * **屏蔽变量** (可选):如果选中,则变量的**值**将不会显示在作业日志中. 如果该值不满足[屏蔽要求,](#masked-variable-requirements)则不会保存该变量. 创建变量后,您可以通过点击 **编辑**按钮. ### Enable or disable UI interface for instance-level CI/CD variables[](#enable-or-disable-ui-interface-for-instance-level-cicd-variables "Permalink") 实例级 CI / CD 变量的 UI 界面正在开发中,但可用于生产环境. 它部署在**默认情况下启用**的功能标志的后面. [有权访问 GitLab Rails 控制台的 GitLab 管理员](../../administration/feature_flags.html)可以选择为您的实例禁用它. 禁用它: ``` Feature.disable(:instance_variables_ui) ``` 要启用它: ``` Feature.enable(:instance_variables_ui) ``` ## Inherit environment variables[](#inherit-environment-variables "Permalink") 版本历史 * [介绍](https://gitlab.com/gitlab-org/gitlab/-/issues/22638)在 GitLab 13.0 后面的禁用[功能标志](../../administration/feature_flags.html) : `ci_dependency_variables` . * 在 GitLab 13.1 中[已删除功能标记](https://gitlab.com/gitlab-org/gitlab/-/issues/217834) . 您可以从相关作业中继承环境变量. 该功能利用了[`artifacts:reports:dotenv`](../pipelines/job_artifacts.html#artifactsreportsdotenv)报告功能. 带有[`dependencies`](../yaml/README.html#dependencies)关键字的示例. ``` build: stage: build script: - echo "BUILD_VERSION=hello" >> build.env artifacts: reports: dotenv: build.env deploy: stage: deploy script: - echo $BUILD_VERSION # => hello dependencies: - build ``` 带[`needs`](../yaml/README.html#artifact-downloads-with-needs)关键字的示例: ``` build: stage: build script: - echo "BUILD_VERSION=hello" >> build.env artifacts: reports: dotenv: build.env deploy: stage: deploy script: - echo $BUILD_VERSION # => hello needs: - job: build artifacts: true ``` ## Priority of environment variables[](#priority-of-environment-variables "Permalink") 不同类型的变量可以优先于其他变量,具体取决于它们的定义位置. 变量的优先顺序为(从最高到最低): 1. [触发器变量](../triggers/README.html#making-use-of-trigger-variables) , [计划的管道变量](../pipelines/schedules.html#using-variables)和[手动管道运行变量](#override-a-variable-by-manually-running-a-pipeline) . 2. Project-level [variables](#custom-environment-variables) or [protected variables](#protect-a-custom-variable). 3. Group-level [variables](#group-level-environment-variables) or [protected variables](#protect-a-custom-variable). 4. [Inherited environment variables](#inherit-environment-variables). 5. YAML-defined [job-level variables](../yaml/README.html#variables). 6. YAML-defined [global variables](../yaml/README.html#variables). 7. [Deployment variables](#deployment-environment-variables). 8. [Predefined environment variables](predefined_variables.html). 例如,如果您定义: * `API_TOKEN=secure`作为项目变量. * 您的`.gitlab-ci.yml` `API_TOKEN=yaml` . `API_TOKEN`将采用`secure`值,因为项目变量优先于`.gitlab-ci.yml`定义`.gitlab-ci.yml` . ## Unsupported variables[](#unsupported-variables "Permalink") Variable names are limited by the underlying shell used to execute scripts (see [available shells](https://docs.gitlab.com/runner/shells/index.html). Each shell has its own unique set of reserved variable names. You will also want to keep in mind the [scope of environment variables](where_variables_can_be_used.html) to ensure a variable is defined in the scope in which you wish to use it. ## Where variables can be used[](#where-variables-can-be-used "Permalink") 单击[此处](where_variables_can_be_used.html)以获得描述在何处以及如何使用不同类型的变量的部分. ## Advanced use[](#advanced-use "Permalink") ### Limit the environment scopes of environment variables[](#limit-the-environment-scopes-of-environment-variables "Permalink") 您可以通过[定义](../environments/index.html)变量可用于的环境来限制变量的环境范围. 要了解有关范围界定环境的更多信息,请参阅[使用规范范围界定环境](../environments/index.html#scoping-environments-with-specs) . ### Deployment environment variables[](#deployment-environment-variables "Permalink") 在 GitLab 8.15 中引入. 负责部署配置的[集成](../../user/project/integrations/overview.html)可以定义在构建环境中设置的自己的变量. 这些变量仅为[部署作业](../environments/index.html)定义. 请查阅所用集成的文档,以了解它们定义了哪些变量. 定义部署变量的示例集成是[Kubernetes 集成](../../user/project/clusters/index.html#deployment-variables) . ### Auto DevOps environment variables[](#auto-devops-environment-variables "Permalink") 在 GitLab 11.7 中[引入](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/49056) . 您可以配置[Auto DevOps,](../../topics/autodevops/index.html)以将 CI 变量传递给正在运行的应用程序,方法是在变量的键之前添加`K8S_SECRET_` . 然后,这些[前缀变量](../../topics/autodevops/customize.html#application-secret-variables)将在运行的应用程序容器上用作环境变量. **警告:**由于当前 Auto DevOps 脚本环境的限制,当前不支持具有多行值的变量. ### Override a variable by manually running a pipeline[](#override-a-variable-by-manually-running-a-pipeline "Permalink") 在 GitLab 10.8 中[引入](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/44059) . 您可以通过[手动运行管道](../pipelines/index.html#run-a-pipeline-manually)来覆盖当前变量的值. 例如,假设您添加了一个名为`$TEST`的自定义变量,并且想在手动管道中覆盖它. 导航到项目的**CI / CD>管道** ,然后单击**运行管道** . 选择要为其运行管道的分支,然后在 UI 中添加变量及其值: [![Override variable value](https://img.kancloud.cn/35/20/35204667767f23a7eafafaa746222e79_1014x330.png)](img/override_variable_manual_pipeline.png) 运行器将覆盖先前设置的值,并将自定义值用于此特定管道. [![Manually overridden variable output](https://img.kancloud.cn/28/12/28121a9f09b8681817aed9edcdca65d0_1676x926.png)](img/override_value_via_manual_pipeline_output.png) ## Environment variables expressions[](#environment-variables-expressions "Permalink") 版本历史 * 在 GitLab 10.7 中[引入](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/37397) [了`only`和`except` CI 关键字](../yaml/README.html#onlyexcept-advanced) * 在 GitLab 12.3 中使用[`rules`关键字](../yaml/README.html#rules) [扩展](https://gitlab.com/gitlab-org/gitlab/-/issues/27863) 使用变量表达式来限制将更改推送到 GitLab 之后在管道中创建的作业. 在`.gitlab-ci.yml` ,变量表达式可同时用于以下两种情况: * [`rules`](../yaml/README.html#rules) ,这是推荐的方法,以及 * [`only`和`except`](../yaml/README.html#onlyexcept-basic) ,它们是不推荐使用的候选对象. 与变量和触发的管道变量结合使用时,这特别有用. ``` deploy: script: cap staging deploy environment: staging only: variables: - $RELEASE == "staging" - $STAGING ``` 在创建管道之前,将对提供的每个表达式进行求值. 如果`only`使用时`variables`任何条件评估为 true,则会创建一个新作业. 如果在使用`except`任何表达式的结果为 true,则不会创建作业. 这遵循[`only` / `except`策略](../yaml/README.html#onlyexcept-advanced)的常规规则. ### Syntax of environment variable expressions[](#syntax-of-environment-variable-expressions "Permalink") 您可以在下面找到受支持的语法参考: 1. 使用字符串进行相等匹配 Examples: * `$VARIABLE == "some value"` * `$VARIABLE != "some value"` (在 GitLab 11.11 中引入) 您可以使用等于运算符`==`或`!=`将变量内容与字符串进行比较. 我们支持双引号和单引号来定义字符串值,因此同时支持`$VARIABLE == "some value"`和`$VARIABLE == 'some value'` . `"some value" == $VARIABLE`也正确. 2. 检查未定义的值 Examples: * `$VARIABLE == null` * `$VARIABLE != null` (在 GitLab 11.11 中引入) 有时,您可能想检查是否定义了变量. 为此,您可以将变量与`null`关键字进行比较,例如`$VARIABLE == null` . 如果在使用`==`时未定义变量,则该表达式的值为 true;如果使用`!=`则该表达式的值为 false. 3. 检查空变量 Examples: * `$VARIABLE == ""` * `$VARIABLE != ""` (introduced in GitLab 11.11) 如果要检查变量是否已定义但为空,则可以将其与空字符串(例如`$VAR == ''`或非空字符串`$VARIABLE != ""` . 4. 比较两个变量 Examples: * `$VARIABLE_1 == $VARIABLE_2` * `$VARIABLE_1 != $VARIABLE_2` (在 GitLab 11.11 中引入) 可以比较两个变量. 这将比较这些变量的值. 5. 可变状态检查 Example: `$STAGING` 如果只想在存在某个变量时创建作业,这意味着它是已定义且非空的,则可以简单地使用变量名作为表达式,例如`$STAGING` . 如果`$STAGING`变量已定义且不为空,则表达式将求值为真. `$STAGING`值必须是长度大于零的字符串. 仅包含空格字符的变量不是空变量. 6. 模式匹配(在 GitLab 11.0 中引入) Examples: * `=~` :如果模式匹配则为真. 例如: `$VARIABLE =~ /^content.*/` * `!~` :如果模式不匹配,则为 true. 例如: `$VARIABLE_1 !~ /^content.*/` (在 GitLab 11.11 中[引入](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/61900) ) 与正则表达式匹配的变量模式使用[RE2 正则表达式语法](https://github.com/google/re2/wiki/Syntax) . 如果满足以下条件,则表达式的计算结果为`true` : * 使用`=~`时找到匹配项. * 当使用火柴都*没有*发现`!~` 模式匹配默认情况下区分大小写. 使用`i`标志修饰符,例如`/pattern/i` ,使模式不区分大小写. 7. Conjunction / Disjunction ([introduced](https://gitlab.com/gitlab-org/gitlab-foss/-/merge_requests/27925) in GitLab 12.0) Examples: * `$VARIABLE1 =~ /^content.*/ && $VARIABLE2 == "something"` * `$VARIABLE1 =~ /^content.*/ && $VARIABLE2 =~ /thing$/ && $VARIABLE3` * `$VARIABLE1 =~ /^content.*/ || $VARIABLE2 =~ /thing$/ && $VARIABLE3` 可以使用`&&`或`||`加入多个条件 . 任何在其他情况下受支持的语法都可以在合并或不合并语句中使用. 运算符的优先级遵循[Ruby 2.5 标准](https://ruby-doc.org/core-2.5.0/doc/syntax/precedence_rdoc.html) ,因此`&&`在`||`之前进行评估 . ### Storing regular expressions in variables[](#storing-regular-expressions-in-variables "Permalink") 可以将正则表达式存储在变量中,以用于模式匹配: ``` variables: STAGINGRELS: '/staging0|staging1/' deploy_staging: script: do.sh deploy staging environment: staging rules: - if: '$RELEASE =~ $STAGINGRELS' ``` **注意:**可用的正则表达式语法受到限制. 有关更多详细信息,请参见[相关问题](https://gitlab.com/gitlab-org/gitlab/-/issues/35438) . 如果需要,您可以使用测试管道来确定正则表达式是否可以在变量中工作. 下面的示例直接从变量内部测试`^mast.*`正则表达式: ``` variables: MYSTRING: 'master' MYREGEX: '/^mast.*/' testdirect: script: /bin/true rules: - if: '$MYSTRING =~ /^mast.*/' testvariable: script: /bin/true rules: - if: '$MYSTRING =~ $MYREGEX' ``` ## Debug logging[](#debug-logging "Permalink") 在 GitLab Runner 1.7 中引入. **警告:**启用调试跟踪可能会严重影响安全性. 输出**将**包含所有变量和其他任何秘密的内容! 输出**将**上传到 GitLab 服务器,并在作业日志中显示! 默认情况下,GitLab Runner 隐藏处理作业时所执行操作的大多数细节. 此行为使作业日志简短,并防止机密信息泄露到日志中,除非您的脚本将其写入屏幕. 如果一项工作没有按预期进行,则可能使问题难以调查. 在这种情况下,您可以在`.gitlab-ci.yml`启用调试跟踪. 在 GitLab Runner v1.7 +上可用,此功能启用外壳程序的执行日志,从而产生详细的作业日志,其中列出了所有已运行的命令,已设置的变量等. 在启用此功能之前,您应确保作业[仅对团队成员](../../user/permissions.html#project-features)可见. 您还应该[清除](../pipelines/index.html#view-jobs-in-a-pipeline)所有生成的作业日志,然后才能再次显示它们. 要启用调试日志(跟踪),请将`CI_DEBUG_TRACE`变量设置为`true` : ``` job_name: variables: CI_DEBUG_TRACE: "true" ``` 将`CI_DEBUG_TRACE`设置为`true`示例截断输出: ``` ... export CI_SERVER_TLS_CA_FILE="/builds/gitlab-examples/ci-debug-trace.tmp/CI_SERVER_TLS_CA_FILE" if [[ -d "/builds/gitlab-examples/ci-debug-trace/.git" ]]; then echo $'\''\x1b[32;1mFetching changes...\x1b[0;m'\'' $'\''cd'\'' "/builds/gitlab-examples/ci-debug-trace" $'\''git'\'' "config" "fetch.recurseSubmodules" "false" $'\''rm'\'' "-f" ".git/index.lock" $'\''git'\'' "clean" "-ffdx" $'\''git'\'' "reset" "--hard" $'\''git'\'' "remote" "set-url" "origin" "https://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@example.com/gitlab-examples/ci-debug-trace.git" $'\''git'\'' "fetch" "origin" "--prune" "+refs/heads/*:refs/remotes/origin/*" "+refs/tags/*:refs/tags/lds" ++ CI_BUILDS_DIR=/builds ++ export CI_PROJECT_DIR=/builds/gitlab-examples/ci-debug-trace ++ CI_PROJECT_DIR=/builds/gitlab-examples/ci-debug-trace ++ export CI_CONCURRENT_ID=87 ++ CI_CONCURRENT_ID=87 ++ export CI_CONCURRENT_PROJECT_ID=0 ++ CI_CONCURRENT_PROJECT_ID=0 ++ export CI_SERVER=yes ++ CI_SERVER=yes ++ mkdir -p /builds/gitlab-examples/ci-debug-trace.tmp ++ echo -n '-----BEGIN CERTIFICATE----- -----END CERTIFICATE-----' ++ export CI_SERVER_TLS_CA_FILE=/builds/gitlab-examples/ci-debug-trace.tmp/CI_SERVER_TLS_CA_FILE ++ CI_SERVER_TLS_CA_FILE=/builds/gitlab-examples/ci-debug-trace.tmp/CI_SERVER_TLS_CA_FILE ++ export CI_PIPELINE_ID=52666 ++ CI_PIPELINE_ID=52666 ++ export CI_PIPELINE_URL=https://gitlab.com/gitlab-examples/ci-debug-trace/pipelines/52666 ++ CI_PIPELINE_URL=https://gitlab.com/gitlab-examples/ci-debug-trace/pipelines/52666 ++ export CI_JOB_ID=7046507 ++ CI_JOB_ID=7046507 ++ export CI_JOB_URL=https://gitlab.com/gitlab-examples/ci-debug-trace/-/jobs/379424655 ++ CI_JOB_URL=https://gitlab.com/gitlab-examples/ci-debug-trace/-/jobs/379424655 ++ export CI_JOB_TOKEN=[MASKED] ++ CI_JOB_TOKEN=[MASKED] ++ export CI_BUILD_ID=379424655 ++ CI_BUILD_ID=379424655 ++ export CI_BUILD_TOKEN=[MASKED] ++ CI_BUILD_TOKEN=[MASKED] ++ export CI_REGISTRY_USER=gitlab-ci-token ++ CI_REGISTRY_USER=gitlab-ci-token ++ export CI_REGISTRY_PASSWORD=[MASKED] ++ CI_REGISTRY_PASSWORD=[MASKED] ++ export CI_REPOSITORY_URL=https://gitlab-ci-token:[MASKED]@gitlab.com/gitlab-examples/ci-debug-trace.git ++ CI_REPOSITORY_URL=https://gitlab-ci-token:[MASKED]@gitlab.com/gitlab-examples/ci-debug-trace.git ++ export CI_JOB_NAME=debug_trace ++ CI_JOB_NAME=debug_trace ++ export CI_JOB_STAGE=test ++ CI_JOB_STAGE=test ++ export CI_NODE_TOTAL=1 ++ CI_NODE_TOTAL=1 ++ export CI_BUILD_NAME=debug_trace ++ CI_BUILD_NAME=debug_trace ++ export CI_BUILD_STAGE=test ++ CI_BUILD_STAGE=test ++ export CI=true ++ CI=true ++ export GITLAB_CI=true ++ GITLAB_CI=true ++ export CI_SERVER_URL=https://gitlab.com:3000 ++ CI_SERVER_URL=https://gitlab.com:3000 ++ export CI_SERVER_HOST=gitlab.com ++ CI_SERVER_HOST=gitlab.com ++ export CI_SERVER_PORT=3000 ++ CI_SERVER_PORT=3000 ++ export CI_SERVER_PROTOCOL=https ++ CI_SERVER_PROTOCOL=https ++ export CI_SERVER_NAME=GitLab ++ CI_SERVER_NAME=GitLab ++ export CI_SERVER_VERSION=12.6.0-pre ++ CI_SERVER_VERSION=12.6.0-pre ++ export CI_SERVER_VERSION_MAJOR=12 ++ CI_SERVER_VERSION_MAJOR=12 ++ export CI_SERVER_VERSION_MINOR=6 ++ CI_SERVER_VERSION_MINOR=6 ++ export CI_SERVER_VERSION_PATCH=0 ++ CI_SERVER_VERSION_PATCH=0 ++ export CI_SERVER_REVISION=f4cc00ae823 ++ CI_SERVER_REVISION=f4cc00ae823 ++ export GITLAB_FEATURES=audit_events,burndown_charts,code_owners,contribution_analytics,description_diffs,elastic_search,group_bulk_edit,group_burndown_charts,group_webhooks,issuable_default_templates,issue_weights,jenkins_integration,ldap_group_sync,member_lock,merge_request_approvers,multiple_issue_assignees,multiple_ldap_servers,multiple_merge_request_assignees,protected_refs_for_users,push_rules,related_issues,repository_mirrors,repository_size_limit,scoped_issue_board,usage_quotas,visual_review_app,wip_limits,adjourned_deletion_for_projects_and_groups,admin_audit_log,auditor_user,batch_comments,blocking_merge_requests,board_assignee_lists,board_milestone_lists,ci_cd_projects,cluster_deployments,code_analytics,code_owner_approval_required,commit_committer_check,cross_project_pipelines,custom_file_templates,custom_file_templates_for_namespace,custom_project_templates,custom_prometheus_metrics,cycle_analytics_for_groups,db_load_balancing,default_project_deletion_protection,dependency_proxy,deploy_board,design_management,email_additional_text,extended_audit_events,external_authorization_service_api_management,feature_flags,file_locks,geo,github_project_service_integration,group_allowed_email_domains,group_project_templates,group_saml,issues_analytics,jira_dev_panel_integration,ldap_group_sync_filter,merge_pipelines,merge_request_performance_metrics,merge_trains,metrics_reports,multiple_approval_rules,multiple_group_issue_boards,object_storage,operations_dashboard,packages,productivity_analytics,project_aliases,protected_environments,reject_unsigned_commits,required_ci_templates,scoped_labels,service_desk,smartcard_auth,group_timelogs,type_of_work_analytics,unprotection_restrictions,ci_project_subscriptions,container_scanning,dast,dependency_scanning,epics,group_ip_restriction,incident_management,insights,license_management,personal_access_token_expiration_policy,pod_logs,prometheus_alerts,pseudonymizer,report_approver_rules,sast,security_dashboard,tracing,web_ide_terminal ++ GITLAB_FEATURES=audit_events,burndown_charts,code_owners,contribution_analytics,description_diffs,elastic_search,group_bulk_edit,group_burndown_charts,group_webhooks,issuable_default_templates,issue_weights,jenkins_integration,ldap_group_sync,member_lock,merge_request_approvers,multiple_issue_assignees,multiple_ldap_servers,multiple_merge_request_assignees,protected_refs_for_users,push_rules,related_issues,repository_mirrors,repository_size_limit,scoped_issue_board,usage_quotas,visual_review_app,wip_limits,adjourned_deletion_for_projects_and_groups,admin_audit_log,auditor_user,batch_comments,blocking_merge_requests,board_assignee_lists,board_milestone_lists,ci_cd_projects,cluster_deployments,code_analytics,code_owner_approval_required,commit_committer_check,cross_project_pipelines,custom_file_templates,custom_file_templates_for_namespace,custom_project_templates,custom_prometheus_metrics,cycle_analytics_for_groups,db_load_balancing,default_project_deletion_protection,dependency_proxy,deploy_board,design_management,email_additional_text,extended_audit_events,external_authorization_service_api_management,feature_flags,file_locks,geo,github_project_service_integration,group_allowed_email_domains,group_project_templates,group_saml,issues_analytics,jira_dev_panel_integration,ldap_group_sync_filter,merge_pipelines,merge_request_performance_metrics,merge_trains,metrics_reports,multiple_approval_rules,multiple_group_issue_boards,object_storage,operations_dashboard,packages,productivity_analytics,project_aliases,protected_environments,reject_unsigned_commits,required_ci_templates,scoped_labels,service_desk,smartcard_auth,group_timelogs,type_of_work_analytics,unprotection_restrictions,ci_project_subscriptions,cluster_health,container_scanning,dast,dependency_scanning,epics,group_ip_restriction,incident_management,insights,license_management,personal_access_token_expiration_policy,pod_logs,prometheus_alerts,pseudonymizer,report_approver_rules,sast,security_dashboard,tracing,web_ide_terminal ++ export CI_PROJECT_ID=17893 ++ CI_PROJECT_ID=17893 ++ export CI_PROJECT_NAME=ci-debug-trace ++ CI_PROJECT_NAME=ci-debug-trace ++ export CI_PROJECT_TITLE='GitLab FOSS' ++ CI_PROJECT_TITLE='GitLab FOSS' ++ export CI_PROJECT_PATH=gitlab-examples/ci-debug-trace ++ CI_PROJECT_PATH=gitlab-examples/ci-debug-trace ++ export CI_PROJECT_PATH_SLUG=gitlab-examples-ci-debug-trace ++ CI_PROJECT_PATH_SLUG=gitlab-examples-ci-debug-trace ++ export CI_PROJECT_NAMESPACE=gitlab-examples ++ CI_PROJECT_NAMESPACE=gitlab-examples ++ export CI_PROJECT_ROOT_NAMESPACE=gitlab-examples ++ CI_PROJECT_ROOT_NAMESPACE=gitlab-examples ++ export CI_PROJECT_URL=https://gitlab.com/gitlab-examples/ci-debug-trace ++ CI_PROJECT_URL=https://gitlab.com/gitlab-examples/ci-debug-trace ++ export CI_PROJECT_VISIBILITY=public ++ CI_PROJECT_VISIBILITY=public ++ export CI_PROJECT_REPOSITORY_LANGUAGES= ++ CI_PROJECT_REPOSITORY_LANGUAGES= ++ export CI_DEFAULT_BRANCH=master ++ CI_DEFAULT_BRANCH=master ++ export CI_REGISTRY=registry.gitlab.com ++ CI_REGISTRY=registry.gitlab.com ++ export CI_API_V4_URL=https://gitlab.com/api/v4 ++ CI_API_V4_URL=https://gitlab.com/api/v4 ++ export CI_PIPELINE_IID=123 ++ CI_PIPELINE_IID=123 ++ export CI_PIPELINE_SOURCE=web ++ CI_PIPELINE_SOURCE=web ++ export CI_CONFIG_PATH=.gitlab-ci.yml ++ CI_CONFIG_PATH=.gitlab-ci.yml ++ export CI_COMMIT_SHA=dd648b2e48ce6518303b0bb580b2ee32fadaf045 ++ CI_COMMIT_SHA=dd648b2e48ce6518303b0bb580b2ee32fadaf045 ++ export CI_COMMIT_SHORT_SHA=dd648b2e ++ CI_COMMIT_SHORT_SHA=dd648b2e ++ export CI_COMMIT_BEFORE_SHA=0000000000000000000000000000000000000000 ++ CI_COMMIT_BEFORE_SHA=0000000000000000000000000000000000000000 ++ export CI_COMMIT_REF_NAME=master ++ CI_COMMIT_REF_NAME=master ++ export CI_COMMIT_REF_SLUG=master ++ CI_COMMIT_REF_SLUG=master ++ export CI_COMMIT_MESSAGE=s/CI/Runner ++ CI_COMMIT_MESSAGE=s/CI/Runner ++ export CI_COMMIT_TITLE=s/CI/Runner ++ CI_COMMIT_TITLE=s/CI/Runner ++ export CI_COMMIT_DESCRIPTION= ++ CI_COMMIT_DESCRIPTION= ++ export CI_COMMIT_REF_PROTECTED=true ++ CI_COMMIT_REF_PROTECTED=true ++ export CI_BUILD_REF=dd648b2e48ce6518303b0bb580b2ee32fadaf045 ++ CI_BUILD_REF=dd648b2e48ce6518303b0bb580b2ee32fadaf045 ++ export CI_BUILD_BEFORE_SHA=0000000000000000000000000000000000000000 ++ CI_BUILD_BEFORE_SHA=0000000000000000000000000000000000000000 ++ export CI_BUILD_REF_NAME=master ++ CI_BUILD_REF_NAME=master ++ export CI_BUILD_REF_SLUG=master ++ CI_BUILD_REF_SLUG=master ++ export CI_RUNNER_ID=1337 ++ CI_RUNNER_ID=1337 ++ export CI_RUNNER_DESCRIPTION=shared-runners-manager-4.gitlab.com ++ CI_RUNNER_DESCRIPTION=shared-runners-manager-4.gitlab.com ++ export 'CI_RUNNER_TAGS=gce, east-c, shared, docker, linux, ruby, mysql, postgres, mongo, git-annex' ++ CI_RUNNER_TAGS='gce, east-c, shared, docker, linux, ruby, mysql, postgres, mongo, git-annex' ++ export CI_DEBUG_TRACE=true ++ CI_DEBUG_TRACE=true ++ export GITLAB_USER_ID=42 ++ GITLAB_USER_ID=42 ++ export GITLAB_USER_EMAIL=user@example.com ++ GITLAB_USER_EMAIL=user@example.com ++ export GITLAB_USER_LOGIN=root ++ GITLAB_USER_LOGIN=root ++ export 'GITLAB_USER_NAME=User' ++ GITLAB_USER_NAME='User' ++ export CI_DISPOSABLE_ENVIRONMENT=true ++ CI_DISPOSABLE_ENVIRONMENT=true ++ export CI_RUNNER_VERSION=12.5.0 ++ CI_RUNNER_VERSION=12.5.0 ++ export CI_RUNNER_REVISION=577f813d ++ CI_RUNNER_REVISION=577f813d ++ export CI_RUNNER_EXECUTABLE_ARCH=linux/amd64 ++ CI_RUNNER_EXECUTABLE_ARCH=linux/amd64 ++ export VERY_SECURE_VARIABLE=imaverysecurevariable ++ VERY_SECURE_VARIABLE=imaverysecurevariable ... ``` ## Video walkthrough of a working example[](#video-walkthrough-of-a-working-example "Permalink") [使用 GitLab 管理复杂配置数据管理怪兽](https://www.youtube.com/watch?v=v4ZOJ96hAck)视频是[复杂配置数据 Monorepo](https://gitlab.com/guided-explorations/config-data-top-scope/config-data-subscope/config-data-monorepo)工作示例项目的演练. 它解释了如何将多个级别的组 CI / CD 变量与环境范围的项目变量组合在一起,以实现应用程序构建或部署的复杂配置. 可以将示例复制到您自己的组或实例中进行测试. 项目页面上提供了有关演示其他 GitLab CI 模式的更多详细信息.