'Use artifacts from merge request job in GitLab CI

In my project I use merge requests to test builds, and deploy once the commit is merged to master. Currently my .gitlab-ci.yml looks like:

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

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

This way only commits that build succesfully get merged to master and deployed. However the build stage runs twice, once in the merge request branch and once in master. I would like to have something like:

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

but the deploy job should have a way to pull the artifact generated by the build job in the merge request branch. Is it possible?



Solution 1:[1]

Check if the CI_MERGE_REQUEST_REF_PATH variable is available.

If so, then perhaps you can use that with the GET /projects/:id/jobs/artifacts/:ref_name/download?job=name API call to download the artifact for the job you want in the most recent successful pipeline for the merge request.

Something like this:

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/*'

Note that both CI_PROJECT_PATH and CI_MERGE_REQUEST_REF_PATH will usually contain / characters. I used sed to change them to the URL-encoded %2F.

Solution 2:[2]

You can get the jobs artifacts using:

curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/<your_project_id>/jobs/artifacts/$CI_COMMIT_REF_NAME/download?job=<your_job_name>"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin Rak
Solution 2 ostergaard