如何消除使用几乎相同阶段的“.gitlab-ci.yml”脚本中的代码重复?

How to eliminate code repitition in a ".gitlab-ci.yml"-script that uses stages that are almost identical?

我有一个 gitlab-ci/cd.yaml 文件可以执行 2 个测试脚本。如您所见,有很多重复发生。事实上,这两个阶段是相同的,除了它们的“脚本”值。

对于烟熏套件,该值为

对于回归套件,该值为

image: node-karma-protractor

stages:
  - suiteSmoke
  - suiteRegression

before_script:
  - npm install

# Smoke suite =================================
smoke_suite:
  stage: suiteSmoke
  tags:
    - docker-in-docker
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - node_modules/
  script:
    - npm run docker_smoke --single-run --progress false
  retry: 1
  #saving the HTML-Report
  artifacts:
    when: on_failure
    paths:
      - reporting/
    expire_in: 1 week
  allow_failure: true

# Regression suite ============================
regression_suite:
  stage: suiteRegression
  tags:
    - docker-in-docker
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - node_modules/
  script:
    - npm run docker_regression --single-run --progress false
  retry: 1
  #saving the HTML-Report
  artifacts:
    when: on_failure
    paths:
      - reporting/
    expire_in: 1 week
  allow_failure: true

脚本需要遵守以下规则:

有没有办法通过抽象来消除所有这些重复?如何实现?

您可以定义模板,然后使用它们扩展您的工作。

文档:https://docs.gitlab.com/ee/ci/yaml/#extends

示例:

.job-template:
  tags:
    - tag
  allow_failure: true

job1:
  extends:
    - .job-template
  script:
    - do something

job2:
  extends:
    - .job-template
  script:
    - do something

Gitlab 提供了几个 mechanisms to prevent duplications in your pipelines namely YAML anchors and the extends 关键字,而建议使用 extends 关键字以提高可读性。

应用于您的示例,您的管道可能如下所示:

image: node-karma-protractor

stages:
  - suiteSmoke
  - suiteRegression

.test:suite:
  stage: suiteSmoke
  tags:
    - docker-in-docker
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - node_modules/
  before_script:
    - npm install
  retry: 1
  #saving the HTML-Report
  artifacts:
    when: on_failure
    paths:
      - reporting/
    expire_in: 1 week
  allow_failure: true

# Smoke suite =================================
smoke_suite:
  extends: .test:suite
  script:
    - npm run docker_smoke --single-run --progress false

# Regression suite ============================
regression_suite:
  extends: .test:suite
  script:
    - npm run docker_regression --single-run --progress false