看看下面的代码片段。我想找到一种方法,可以通过将command_A和command_B放置在job1和job2都运行它的位置来减少重复代码
job1:
script:
- command_A
- command_B
- command_C
job2:
script:
- command_A
- command_B
- command_D
答案 0 :(得分:1)
在您的情况下,可能最简单的方法是使用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
要了解更多信息,我发现this article会有所帮助,当然还有official Gitlab docs on anchors。
或者,您可以将所有通用代码简单地放在before_script
标记中,或使用.extends
关键字-您可以在我的博客上看到some examples。