在 .gitlab-ci.yml 作业之间共享脚本

Sid*_*and 6 gitlab-ci

看看下面的片段。我想找到一种方法来减少重复代码,方法是将 command_A 和 command_B 放置在 job1 和 job2 都运行它的位置

job1:
  script:
    - command_A
    - command_B
    - command_C

job2:
  script: 
    - command_A
    - command_B
    - command_D
Run Code Online (Sandbox Code Playgroud)

Cor*_*ina 6

就您而言,最简单的方法可能是使用 YML 锚点。

锚点是 YML 重用代码的方式 - 您可以将它们想象成有点像函数。

您可以在某处定义配置块并使用&. 然后,您可以将其与 一起使用*。

# Create an anchor called `&common`
.common: &common
  - command_A
  - command_B

job1:
  script:
   # Merge the anchor into the `script` using `<<*:`
    - *common
    - command_C

job2:
  script: 
    - *common
    - command_D
Run Code Online (Sandbox Code Playgroud)

要了解更多信息,我发现这篇文章很有帮助,当然还有关于锚点的 Gitlab 官方文档。

或者,您可以简单地将所有常见代码放在before_script标签中或使用.extends关键字 - 您可以在我的博客上看到一些示例。

  • 要合并脚本,语法应为“- *common”,不带“&lt;&lt;:”。否则 `command_C` 和 `command_D` 将不会运行。https://docs.gitlab.com/ee/ci/yaml/yaml_specific_features.html#yaml-anchors-for-scripts (2认同)