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

Viewed 506

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

2 Answers

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.

Found the answer here

.before_script_template:
  before_script:
    - apt-get update
    - apt-get -y install apt-transport-https ca-certificates curl gnupg2 software-properties-common
    - curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
    - add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
    - apt-get update
    - apt-get -y install docker-ce
    - curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    - chmod +x /usr/local/bin/docker-compose
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY

test_integration:
  extends: .before_script_template
  stage: test 
  script:
    - docker-compose -f CI/backend-service/docker-compose.yml up -d
    - npm install
    - npm run-script integration-test

build:
  extends: .before_script_template
  stage: build
  script:
    - npm install
    - export VERSION=`git describe --tags --always`
    - docker build -t $CI_REGISTRY_IMAGE:$VERSION .
    - docker push $CI_REGISTRY_IMAGE

etc

Related