在GitLab CI中使用合并请求作业中的工件

时间:2020-10-01 01:46:38

标签: gitlab gitlab-ci

在我的项目中,我使用合并请求来测试构建,并在提交合并到主服务器后进行部署。目前,我的.gitlab-ci.yml如下:

build:
  stage: build
  script:
    - yarn build
  artifacts:
    paths:
      - public

deploy:
  stage: deploy
  script: yarn deploy
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

这样,只有成功构建的提交才可以合并到master并进行部署。但是,构建阶段运行两次,一次在合并请求分支中,一次在主服务器中。我想要类似的东西:

build:
  stage: build
  script:
    - yarn build
  artifacts:
    paths:
      - public
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

deploy:
  stage: deploy
  script: yarn deploy
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

,但是部署作业应该有一种方法来拉动build作业在合并请求分支中生成的工件。有可能吗?

1 个答案:

答案 0 :(得分:0)

检查 CI_MERGE_REQUEST_REF_PATH 变量是否可用。

如果是这样,那么也许您可以将其与 GET /projects/:id/jobs/artifacts/:ref_name/download?job=name API 调用一起使用,以在合并请求的最近成功管道中下载您想要的作业的工件。

像这样:

rules:
  - if: ${CI_PIPELINE_SOURCE} == "merge_request_event"
script:
    # Download the binaries from the most recent successful pipeline for the CI_MERGE_REQUEST_REF_PATH
    # See: https://docs.gitlab.com/ee/api/job_artifacts.html#download-the-artifacts-archive
    - echo Downloading ${CI_API_V4_URL}/projects/$(echo ${CI_PROJECT_PATH} | sed "s/\//%2F/g")/jobs/artifacts/$(echo ${CI_MERGE_REQUEST_REF_PATH} | sed "s/\//%2F/g")/download?job=build
    # Because of the ':' in the header, the whole curl command must be inside single-quotes
    - 'curl
       --header "JOB-TOKEN: ${CI_JOB_TOKEN}"
       --output ${CI_PROJECT_DIR}/artifacts.zip
       ${CI_API_V4_URL}/projects/$(echo ${CI_PROJECT_PATH} | sed "s/\//%2F/g")/jobs/artifacts/$(echo ${CI_MERGE_REQUEST_REF_PATH} | sed "s/\//%2F/g")/download?job=build'
    # extract desired artifacts from the zip file.
    - unzip
       -o
       -d ${CI_BUILDS_DIR}/${CI_PROJECT_NAMESPACE}
       ${CI_PROJECT_DIR}/artifacts.zip
       'directory/subDirectory/*'

请注意 CI_PROJECT_PATH 和 CI_MERGE_REQUEST_REF_PATH 通常都包含 / 字符。我使用 sed 将它们更改为 URL 编码的 %2F