【发布时间】:2021-02-19 14:47:37
【问题描述】:
我正在尝试使用 .gitlab-ci.yml 设置代码重复最少的 CI。
这样,我将配置分离到单独的文件中,并重用其中常见的部分。
我有一个带有 Gitlab CI 设置的单独存储库:gitlab-ci 和几个使用它来形成自己的 CI 管道的项目。
gitlab-ci 仓库的内容
template_jobs.yml:
.sample:
rules:
- if: '$CI_PIPELINE_SOURCE == "push"'
when: on_success
- when: never
jobs_architectureA.yml:
include:
- local: '/template_jobs.yml'
.script_core: &script_core
- echo "Running stage"
test_archA:
extends:
- .sample
stage: test
tags:
- architectureA
script:
- *script_core
jobs_architectureB.yml:
include:
- local: '/template_jobs.yml'
.script_core: &script_core
- echo "Running stage"
test_archB:
extends:
- .sample
stage: test
tags:
- architectureB
script:
- *script_core
项目代码内容:
在实际项目中(每个项目有单独的存储库,我有很多),我有以下内容:
.gitlab-ci.yml:
stages:
- test
include:
- project: 'gitlab-ci'
file: '/jobs_architectureA.yml'
- project: 'gitlab-ci'
file: '/jobs_architectureB.yml'
此配置工作正常,允许仅包含某些模块的某些架构,同时在作业模板之间共享规则。
但是,很容易注意到一个代码重复:jobs_architectureA.yml 和 jobs_architectureB.yml 都包含一个公共部分:
.script_core: &script_core
- echo "Running stage"
最好将其移动到单独的文件中:template_scripts.yml 并同时包含 jobs_architectureA.yml* 和 jobs_architectureB.yml。但是,这会导致 YAML 无效(至少从 Gitlab 的角度来看)。
有了这个,我得出一个结论,我可以分享这些规则,因为它们的使用机制是通过extends关键字;但是,我无法使用脚本来执行此操作:因为它在 YAML 级别使用 &/* anchoring 机制。
理想情况下,我想要以下内容:
理想(概念上)gitlab-ci 存储库的内容
template_jobs.yml:
.sample:
rules:
- if: '$CI_PIPELINE_SOURCE == "push"'
when: on_success
- when: never
template_scripts.yml:
.script_core: &script_core
- echo "Running stage"
jobs_architectureA.yml:
include:
- local: '/template_jobs.yml'
- local: '/template_scripts.yml'
test_archA:
extends:
- .sample
stage: test
tags:
- architectureA
script:
- *script_core # this becomes invalid, as script_core is in the other file, even though it is included at the top
jobs_architectureB.yml:
include:
- local: '/template_jobs.yml'
- local: '/template_scripts.yml'
test_archB:
extends:
- .sample
stage: test
tags:
- architectureB
script:
- *script_core # this becomes invalid, as script_core is in the other file, even though it is included at the top
- 我做错了吗?
- 我是否遇到了 Gitlab 机制的限制?是不是在这个特定的 YML 类型中实现了
include指令,这限制了我? - 我是否可以选择实现接近所需行为的东西?
请注意,虽然这可能看起来没什么大不了的,但实际上,我的脚本还有很多,实际的脚本要大得多。因此,目前是到处都是重复代码,很容易出错。
【问题讨论】: