Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GitLab CI: Get source branch after merge-request has been accepted

I have a master branch which is supposed to only get commits by merging either a "release/xxxxx" branch into it or by merging a "hotfix/xxxxx" branch into it.

The pipeline for a release branch builds a docker image and publishes it using the tag "beta".
The pipeline for a release branch builds a docker image and publishes it using the tag "hotfix".

The pipeline for the master simply re-tags either "beta" to "stable" (when a release branch has been merged into the master) or "hotfix" to "stable" (when a hotfix branch has been merged into the master). Then it also creates a new git tag for that version and a release in gitlab. Finally the docker image gets deployed.

Currently the following happens:

  • A merge request is created to merge "release/xxxxx" into "master".
  • The pipeline starts automatically (before the merge request has been accepted and merged).
  • The docker job parses the CI_MERGE_REQUEST_SOURCE_BRANCH_NAME variable to determine the source branch of the merge request was a release branch.
  • The docker job then re-tags "beta" to "latest".
  • The git tag job adds a version tag and gitlab release to the project.
  • The deploy job deploys the docker image.

When the merge request is finally accepted the following happens:

  • The pipeline starts again.
  • The docker job parses CI_MERGE_REQUEST_SOURCE_BRANCH_NAME which is now empty and thus fails to determine the source branch for this merge.
  • The docker job fails.

I think it's pretty obvious that I don't want to run all these jobs (especially the deploy job) before the merge request has been accepted.

But I can't think of a good way to only run the pipeline on the master after a merge-request has been accepted and then still be able to determine the source branch.

like image 632
Forivin Avatar asked Jan 23 '20 11:01

Forivin


1 Answers

It seems you can do it through the API of gitlab.

Here is a curl example.

  - MR_BRANCH_LAST_COMMIT_SHA=$(
      curl -s \
        --header "PRIVATE-TOKEN: $CI_PRIVATE_TOKEN" \
        "$CI_API_V4_URL/projects/$CI_PROJECT_ID/repository/commits/$CI_COMMIT_SHA" |\
        jq -r '.parent_ids | del(.[] | select(. == "'$CI_COMMIT_BEFORE_SHA'")) | .[-1]'
    )
  - MR_BRANCH_NAME=$(
      curl -s \
        --header "PRIVATE-TOKEN: $CI_PRIVATE_TOKEN" \
        "$CI_API_V4_URL/projects/$CI_PROJECT_ID/repository/commits/$MR_BRANCH_LAST_COMMIT_SHA/merge_requests" |\
        jq -r '.[0].source_branch'
    )

I found that workaround here: https://forum.gitlab.com/t/run-job-in-ci-pipeline-only-on-merge-branch-into-the-master-and-get-merged-branch-name/24195/5

like image 124
BastienSander Avatar answered Sep 28 '22 11:09

BastienSander