I'm trying to figure out a way to automatically trigger a pipeline for merge requests when there's a push or merge to the target branch, like the main branch. By default, the setup using `if: $CI_PIPELINE_SOURCE == 'merge_request_event'` doesn't give me the functionality I need. It's crucial for us to run tests on merge requests after any updates to the main branch, as those changes could impact the validity of the tests. I'm currently exploring the idea of using server hooks or possibly triggering the merge request test jobs through the API after a push or merge to the main branch. Any suggestions on how to approach this effectively?
4 Answers
On every push to the main branch, you could programmatically fetch all open merge requests targeting it and trigger their pipelines. Using server hooks is possible, but they can complicate maintenance, especially on self-hosted setups. This keeps everything within the GitLab CI environment, making it easier to manage.
One of the cleanest workarounds is to set up an API job. Each time there's a push to the main branch, you can fetch all open merge requests that target the main and then retrigger their pipelines using the pipeline API. GitLab doesn’t directly support rerunning an MR when the target branch changes, but doing it this way works reliably, even if it feels a bit hacky.
I’m curious about your concern with tests becoming invalid after changes to the main branch. Usually, the code in the main branch shouldn’t invalidate tests in your feature branches unless you're testing against the final merge result. If your test setup can ensure this, I’d suggest using a feature like requiring merge requests to be up-to-date before merging, which would naturally cause a new CI run without needing to hack the pipeline.
Our practice is to rebase merge requests prior to merging them and we have the 'Enable merged results pipelines' feature turned on. This ensures that when a merge request is actually merged, it runs against the latest changes. If a new merge request is then submitted after that, it will need to be rebased first, which triggers a full CI test on the updated merge result. We specifically want to avoid running all those pipelines for every minor change in the main branch, especially with multiple merge requests open.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically