Search code examples
devopsgitlab-cipipeline

In Gitlab-ci is there a way to run before scripts only after rule is match


in gitlab-ci I have

before_script:
  - apt update && apt upgrade -y
  - apt install -y 

and in my job on stages I added a rule

merge_request:
  stage: test
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != "master"
    - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "master"

what's happening is that the job is triggered in his stage as the before script is running, then it gets to the rule and sees that there's nothing to do. That slows down the pipeline. Is there a way to have the rule before the "before_script"

here's the pipeline pipeline Thank you


Solution

  • I would rather put the before script commands in a separate stage, and keep the rules in the first stage.

    That way, the first stage triggers only if the rules match.
    It can run the commands of the formerly "before_script".

    And the next stages can go on with your script.