Search code examples
gitlab-cipipeline

is it possible to run a ci/cd pipeline of a project after merge from approved merge request while using merge request predefined variables


I will explain my problem with a scenario to make it clearer.
What I have:

  • main branch (default, protected): have .gitignore + locked cicd.yml file
  • feature branch: copied from main and then added required feature
  • .gitlab-ci.yml file contains build and deploy jobs for the project (needs merge request predefined variables-- title + description)


The wanted scenario:

  1. dev commits changes to feature branch and request a merge to main needs approval -> .gitlab-ci.yml doesn't run
  2. when request is approved then merged -> run .gitlab-ci.yml in main not feature using $CI_MERGE_REQUEST_* predefined variables (title and description)


I have tried the follwing workflow rules

rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_APPROVED && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_MERGE_REQUEST_TITLE =~ /^v\d+(\.\d+){2}$/ && $CI_MERGE_REQUEST_DESCRIPTION != "" && $CI_MERGE_REQUEST_DESCRIPTION =~ $MERGE_REQUEST_DESC_PATTERN && $CI_MERGE_REQUEST_EVENT_TYPE == "merged_result"

I need to check $CI_MERGE_REQUEST_TITLE and $CI_MERGE_REQUEST_DESCRIPTION so they can't be removed (they are also used to build the image $CI_MERGE_REQUEST_TITLE is image tag)

is it possible to achieve this scenario? if not can you suggest a workaround
thank you in advance


Solution

  • I have found a solution of making the pipeline run twice once for merge requests and the other for the actual merge

    1- the pipeline will not run unless the MR/push target is main

    2- in merge request process show validation jobs only $CI_PIPELINE_SOURCE == "merge_request_event" then check the title and description as required.

    3- to reuse merge request values (title and description) as intended, I have changed the settings for commit's messages of merge request to

    %{title} # ----> $CI_MERGE_REQUEST_TITLE mapped to $CI_COMMIT_TITLE
    %{description} # ----> $CI_MERGE_REQUEST_DESCRIPTION mapped to $CI_COMMIT_DESCRIPTION
    

    this way if the merge request was accepted (merged) a new commit will follow the previous template

    4- in push process the build/deploy jobs will use the mapped values to build the image registry/project/image:$CI_COMMIT_TITLE and deploy it, this pipeline will run in main not in merge request

    enter image description here