我有一个 monorepo,其中定义了一堆服务。我希望每个服务都有自己的管道,这样团队就可以独立工作。
这是我的管道代码示例:
.backend:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
changes:
- "backend/**/*"
when: always
backend-build:
stage: build
extends: .backend
needs: []
script:
- echo "Compiling the backend code..."
backend-test:
stage: test
extends: .backend
needs: ["backend-build"]
script:
- echo "Testing the backend code..."
我尝试添加规则并进行更改以在 .gitlab-ci.yml 的根部设置变量,如下所示:
rules:
- changes:
- "backend/**/*"
variables:
TEST_VAR: backend
- changes:
- "frontend/**/*"
variables:
TEST_VAR: frontend
include: '/templates/.example.yml'
但是我收到以下错误:
jobs rules config should implement a script: or a trigger: keyword
。
如何才能保持代码干燥,同时又引用多个
rules:changes:paths
的同一代码块?
我最终使用 Python 生成管道 YAML,创建一个工件,然后使用 YAML 触发子管道。这是我的 .gitlab-ci.yml:
stages:
- triggers
- triggered
- build
- test
- deploy
generate-config-mr:
stage: triggers
image: python:3.11.5-alpine3.18
script:
- pip install -q requests Jinja2
- python gitlab/build-pipeline.py $GENERATED_CONFIG_FILE # Tell the script where the write the config
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
artifacts:
paths:
- $GENERATED_CONFIG_FILE
generate-config-default:
stage: triggers
# Using this image to get the git executable
image: cicirello/pyaction:4.29.0
script:
- pip install -q requests Jinja2 GitPython
- python gitlab/build-pipeline.py $GENERATED_CONFIG_FILE # Tell the script where the write the config
artifacts:
paths:
- $GENERATED_CONFIG_FILE
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
mr-child-pipeline:
stage: triggered
trigger:
include:
- artifact: child-pipeline.yml
job: generate-config-mr
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
default-child-pipeline:
stage: triggered
trigger:
include:
- artifact: child-pipeline.yml
job: generate-config-default
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
我使用 Jinja2 生成 YAML:
{% for cell in variables %}
{{ cell }}-build:
stage: build
image: mycustomimage
script:
- echo "Compiling the {{ cell }} code..."
rules:
- when: on_success
{{ cell }}-test:
stage: test
image: mycustomimage
script:
- echo "Testing the {{ cell }} code..."
rules:
- when: on_success
{% endfor %}