Below is a .gitlab-ci.yml snippet that configures your pipeline to run only for merge request events. In GitLab CI/CD, you can achieve this using the rules keyword in your jobs. This ensures that jobs are not executed for normal pushes (e.g., direct commits to a branch).
Key Concepts:
- Rules Keyword: This is used to define conditions for when a job should run. We're checking the predefined variable
$CI_PIPELINE_SOURCE, which equals "merge_request_event" for merge request pipelines.
- Behavior: If the pipeline is triggered by a normal push, the jobs with these rules will be skipped, and the pipeline will not execute any steps.
- Applicability: Apply this rule to all jobs in your file to ensure the entire pipeline only runs for merge requests.
Here's the snippet:
# Define your stages if needed
stages:
- build
- test
- deploy
# Example job: This job will only run for merge request events
job1:
stage: build
script:
- echo "This pipeline is running for a merge request"
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
# You can add more jobs, but apply the same rules to them
job2:
stage: test
script:
- echo "Running tests for merge request"
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
# Another example for a deploy job
job3:
stage: deploy
script:
- echo "Deploying for merge request"
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
Explanation:
- rules Section: For each job, the
rules array specifies a condition. The job will only be included in the pipeline if $CI_PIPELINE_SOURCE == "merge_request_event". For other events (e.g., pushes), the job is skipped.
- Pipeline Behavior:
- On a merge request: The pipeline runs as normal.
- On a normal push: No jobs will run because they all have rules that exclude them, and the pipeline will be marked as "skipped" or "not created" if there are no matching jobs.
- Best Practices:
- Add the
rules block to every job in your .gitlab-ci.yml file to enforce this behavior across the entire pipeline.
- If you're using an older version of GitLab (pre-12.0), you might need to use
only: [merge_requests] instead, but rules is recommended for modern setups as it's more flexible.
- Test this configuration in your GitLab project to ensure it behaves as expected.
This snippet keeps things simple and focused. If you have more complex pipelines, you can expand it by adding additional jobs or stages while maintaining the rules for each.