是否可以使用分支特定变量重用 gitlab CI 脚本?

Can a gitlab CI script be reused using branch specific variables?

我有一个 gitlab CI 脚本,它使用网络服务器上的运行程序部署网站。有多个部署(取决于分支)。除了文件复制到的 htdocs 目录之外,脚本始终相同。

stages:
  - build
  - deploy

pages:
  stage: build
  script:
  - hugo
  artifacts:
    paths:
    - public/

deploy_to_test:
  stage: deploy
  tags:
    - web-deploy
  script:
    - rsync -av --omit-dir-times --no-owner --delete public/ /var/www/wwwtest.my/
    - find /var/www/wwwtest.my/ -type f -exec chmod 644 {} \;
    - find /var/www/wwwtest.my/ -type d -exec chmod 755 {} \;
  environment:
    name: test
  only:
    - develop


deploy_to_prod:
  stage: deploy
  tags:
    - web-deploy
  script:
    - rsync -av --omit-dir-times --no-owner --delete public/ /var/www/www.my/
    - find /var/www/www.my/ -type f -exec chmod 644 {} \;
    - find /var/www/www.my/ -type d -exec chmod 755 {} \;
  environment:
    name: prod
  only:
    - master

是否有可能以某种方式坚持 DRY 原则,将 htdocs 目录设置为分支因变量并重用部署脚本?

您可以定义一个可以跨作业重复使用的 YAML 模板。 每个作业都可以定义模板化脚本可以使用的自定义变量。

示例:

.template: &template
  stage: deploy
  tags:
    - web-deploy
  script:
    - **Use the $HTDOCS variable**

deploy_to_test:
  <<: *template
  environment:
    name: prod
  variables:
    - HTDOCS: foo
  only:
    - master

更多信息here and here