'Gitlab CI pipeline that starts some jobs at any push and some jobs at push to branch if MR exists OR when MR is created

I want my pipelines to run:

  1. backend_tests job for any push with changes in backend/ folder,
  2. frontend_tests job for any push with changes in frontend/ folder,
  3. old_code_tests job for push with changes in backend/ folder, or when MR is created and there are changes in backend folder in the source branch

My problem is that with the following .gitlab-ci.yml the old_code_tests job will run for any push to the branch with open MR, if there are already changes in the backend folder - even if push did not introduced such changes. I have no idea how to avoid this. The job is created correctly when MR is being created.

In other words: if there already is MR and branch contains backend changes and I push frontend only changes, the old_code_test job should NOT run - and it unexpectedly runs with given configuration.

I do not want to run old_code_tests job if there is no MR for given branch - and it works.

stages:
  - frontend_tests
  - backend_tests
  - old_code



old_code_test:
  extends: .test_old_code_template
  stage: old_code
  needs: []
  script:
    - echo "Test old code"
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
    - if: '$CI_PIPELINE_SOURCE == "push"'
      when: never
    - changes:
      - backend/**/*


backend_tests:
  stage: backend_tests
  needs: []
  extends: .backend_template
  script:
    - echo "Test backend"
  rules:
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_OPEN_MERGE_REQUESTS'
      when: never
    - changes:
      - backend/**/*


frontend_tests:
  stage: frontend_tests
  needs: []
  extends: .frontend_template
  script:
    -  echo "Frontend test"
  rules:
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_OPEN_MERGE_REQUESTS'
      when: never
    - changes:
      - frontend/**/*



Solution 1:[1]

Try to use only keyword in your old_code stage:

only:
  changes:
    - backend/**/*

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 Svyatoslav Kuznetsov