如何在gitlab ci中引用作业规则中的变量?

Ami*_* Ba 5 yaml gitlab gitlab-ci

我需要在 gitlab ci 作业规则中重用变量

include:
  - template: "Workflows/Branch-Pipelines.gitlab-ci.yml"

.staging_variables:
  variables:
    CONFIG_NAME: "staging"

.staging_rules:
  rules:
    - if: $CI_COMMIT_BRANCH == $STAGING_BRANCH
      variables: !reference [.staging_variables, variables]

stages:
  - staging

staging:
  stage: staging
  rules:
    - !reference [.staging_rules, rules]
  script:
    - echo $CONFIG_NAME
  tags:
    - staging
Run Code Online (Sandbox Code Playgroud)

但是,我看到了这个Syntax is incorrectlinting 错误:

jobs:staging:rules:rule:variables config should be a hash of key value pairs
Run Code Online (Sandbox Code Playgroud)

我正在使用这里解释的示例:

https://docs.gitlab.com/ee/ci/yaml/yaml_optimization.html#reference-tags

请注意,我可以做到这一点并且有效:

include:
  - template: "Workflows/Branch-Pipelines.gitlab-ci.yml"

.staging_rules:
  rules:
    - if: $CI_COMMIT_BRANCH == $STAGING_BRANCH
      variables:
          CONFIG_NAME: "staging"

stages:
  - staging

staging:
  stage: staging
  rules:
    - !reference [.staging_rules, rules]
  script:
    - echo $CONFIG_NAME
  tags:
    - staging
Run Code Online (Sandbox Code Playgroud)

Jak*_*kow 5

目前无法!reference在引用的部分中使用-keyword。!reference

\n

!参考文档

\n
\n

您不能\xe2\x80\x99 重用已包含 !reference 标记的部分。仅\n支持一层嵌套。

\n
\n

根据您的需要,您可以使用 YAML 锚点。(未测试)

\n
include:\n  - template: "Workflows/Branch-Pipelines.gitlab-ci.yml"\n\n.staging_variables: &staging_variables\n  variables:\n    CONFIG_NAME: "staging"\n\n.staging_rules: &staging_rules\n  rules:\n    - if: $CI_COMMIT_BRANCH == $STAGING_BRANCH\n      variables: *staging_variables\n\nstages:\n  - staging\n\nstaging:\n  stage: staging\n  rules:\n    - *staging_rules\n  script:\n    - echo $CONFIG_NAME\n  tags:\n    - staging\n
Run Code Online (Sandbox Code Playgroud)\n

更新

\n

从 GitLab 14.8 开始,可以在 、 和 部分中使用最多十层的嵌套引用scriptbefore_scriptafter_script

\n


SPM*_*MSE -1

正如上面的评论所述,您会为 GitLab CI linting 工具生成一个语法错误,该工具尝试解析引用部分中的变量数组。

\n

更改您的配置以具有!reference如下标记:

\n
staging:\n  stage: staging\n  rules: !reference [.staging_rules, rules]\n  script:\n    - echo $CONFIG_NAME\n  tags:\n    - staging\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,这里- !reference已更改为rules: !reference [\xe2\x80\xa6]

\n

这应该可以解决您的错误

\n