I need to trigger the gitlab pipeline automatically when creating a Merge Request. This pipeline should start automatically before clicking on merge. I have written this pipeline but not working as I expected. Now work this by clicking on the merge button. I need this to start with automatically creating a Merge Request.
default:
tags:
- $RUNNER_TAG
stages:
- sonarqube
- merge
# SonarQube scan on the source branch (relative branch)
sonarqube-check:
stage: sonarqube
image: node:slim
cache:
key: "${CI_JOB_NAME}"
paths:
- .sonar/cache
script:
- apt-get update -y
- apt-get install -y git
- git checkout $CI_COMMIT_REF_NAME # Check out the branch related to the MR
- git pull origin $CI_COMMIT_REF_NAME # Pull latest changes
- yarn install
- yarn coverage:ci
- npx sonarqube-scanner -Dproject.settings=./sonar-project-el.properties
# Extract project key from sonar-project.properties
- PROJECT_KEY=$(grep sonar.projectKey sonar-project-el.properties | cut -d '=' -f2)
# Fetch the quality gate result from SonarQube API
- |
QUALITY_GATE=$(curl -s -u $SONAR_LOGIN: $SONAR_HOST_URL/api/qualitygates/project_status?projectKey=$PROJECT_KEY | jq -r .projectStatus.status)
if [ "$QUALITY_GATE" != "OK" ]; then
echo "SonarQube quality gate failed. MR cannot be merged."
exit 1
fi
allow_failure: false
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: never
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
when: always
# Job for the automatic merge, triggered when the SonarQube check passes
merge-to-develop:
stage: merge
image: alpine/git
script:
- git fetch origin
- git checkout develop
- git pull origin develop
- git merge --no-ff origin/$CI_COMMIT_REF_NAME # Merge dynamically determined MR branch into develop
- git push origin develop # Push the merged changes to develop
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop"' # Run only if MR targets develop
when: on_success
How can I solve this issue?