Search code examples
gitlabgitlab-cigitlab-api

Merging a merge request with API and waiting for its pipeline to finish in Gitlab Ci


i am trying to write a ci.yml to automatically create a merge request and merge it and wait until pipeline succeed. In order to do that, i need the pipeline Id of the merge request. but the only pipeline Id that i recieve from the response of merge call is .head_pipeline.id which is the last pipeline id of the project not the one after merging.

i need the actual pipeline id to poll the status. if the status is "success", job will be ended.

i have tried :

`

PIPELINE_ID=`curl --silent -X PUT "${GITLAB_BASE_URL}/${SERVICE_PROJECT_ID}/merge_requests/${MERGE_REQUEST_IID}/merge" --header "Private-Token: ${PRIVATE_TOKEN}" --header "Content-Type: application/json" | jq .head_pipeline.id`

`


Solution

  • here is the solution, that i found. After merge, we can find "merge_commit_sha" as an attribute in rspBody. then we should get all pipelines and find the one that match with that attribute.

    MERGE_COMMIT_SHA=`curl --silent -X GET "${GITLAB_BASE_URL}/${SERVICE_PROJECT_ID}/merge_requests/${MERGE_REQUEST_IID}" --header "Private-Token: ${PRIVATE_TOKEN}" --header "Content-Type: application/json" | jq -r .merge_commit_sha`
    PIPELINE_ID=$(curl --silent -X GET "${GITLAB_BASE_URL}/${SERVICE_PROJECT_ID}/pipelines" --header "Private-Token: ${PRIVATE_TOKEN}" | jq '.[] | select(.ref=='\"$TARGET_BRANCH\"') | select (.sha=='\"$MERGE_COMMIT_SHA\"') | .id')