0

Below CICD code automatically triggers when we push the code into "cicd-setup" branch. Here both "build-stage" and "sonar-stage" both automatically trigger when we PUSH the code into "cicd-setup" branch every time. I don't want to trigger "sonar-stage" automatically, when we push the code. I added only: - merge_requests If i add above code, "sonar-stage" triggers only when we raise MR and other stages won't run when we raise MR and this is half solution!!.

My Question is, "sonar-stage" should not execute/trigger automatically when we PUSH the code every time. It will trigger ONLY when we raise Merge Request.

stages:
  - build-stage
  - sonar-stage

variables:
  SONAR_HOST: "http://asdftestserver01.abc.com:9000"
  SONAR_PROJECT_KEY: "test-api"
  SONAR_LOGIN_TOKEN: "aaabbbbbbcccccccddddddddd"

build_stage:
  stage: build-stage
  only:
    - cicd-setup
  environment:
    name: stage
  script:
    - echo "build stage started"
    - mvn clean install
    
api_sonarqube_analysis:
  stage: sonar-stage
  only:
    - merge_requests
    - cicd-setup    
  script:
    - pwd
    - echo "sonarqube started"
    - mvn sonar:sonar -Dsonar.projectKey=$PROJECT_KEY -Dsonar.host.url=$SONAR_HOST -Dsonar.login=$SONAR_LOGIN_TOKEN 

1 Answers1

1

As you may have seen on the docs, only and except are being deprecated in favour of rules. So perhaps is best for you to migrate to the new syntax - not that you can't achieve the same with only - as it'll also look clearer.

That said, you can adapt to the new format like this:

stages:
  - build-stage
  - sonar-stage

variables:
  SONAR_HOST: "http://asdftestserver01.abc.com:9000"
  SONAR_PROJECT_KEY: "test-api"
  SONAR_LOGIN_TOKEN: "aaabbbbbbcccccccddddddddd"

build_stage:
  stage: build-stage
  rules:
    - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "cicd-setup"
  environment:
    name: stage
  script:
    - echo "build stage started"
    - mvn clean install
    
api_sonarqube_analysis:
  stage: sonar-stage
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME == "cicd-setup"
  script:
    - pwd
    - echo "sonarqube started"
    - mvn sonar:sonar -Dsonar.projectKey=$PROJECT_KEY -Dsonar.host.url=$SONAR_HOST -Dsonar.login=$SONAR_LOGIN_TOKEN 

I have used the variable $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME but you also have available $CI_MERGE_REQUEST_TARGET_BRANCH_NAME in case you want to use it. The full list of Merge Request variables available is here.

Bear in mind that this will generate two separate pipelines when you open an MR, one for each stage, as every push to an MR-related branch will also trigger build_stage job.

bhito
  • 2,083
  • 7
  • 13