44

In .gitlab-ci.yml it is possible to add a default before_script that runs before all script in defined jobs.

My question is why define before_script in a job instead of just using the script in the job? Is using before_script inside a job is only to override the default before_script, or are there other circumstances or reasons for it?

Ouss
  • 2,912
  • 2
  • 25
  • 45

1 Answers1

50

It's mostly useful for jobs to add or override steps when using include: (templates) and/or extends: and/or globals/default for before_script as you mentioned.

For example, you may create a hidden key job that defines script: intended to be extended by other jobs. Those jobs which extend it can provide a before_script: key without overriding script: or vice versa.

.install_dependencies:
  before_script:
    - pip install --upgrade pip
    - pip install -r requirements.txt

my_test_job:
  extends: .install_dependencies
  script:
    - pytest

So, it's just for composition of jobs. Otherwise, there is no difference. before_script: and script: are simply concatenated together when the job runs.

It's worth mentioning also that after_script: is significantly different than script:/before_script:. after_script runs in a separate shell instance and will run under different circumstances. See the docs for more info.

sytech
  • 29,298
  • 3
  • 45
  • 86
  • 1
    To reduce job duration. I want to run `install_dependencies` once!? B/w stages and jobs! Does `extends` help? – Qamar Dec 13 '22 at 12:42
  • 2
    @Qamar that sounds like a separate question. As a hint: look into `cache:` and the [gitlab docs on caching](https://docs.gitlab.com/ee/ci/caching/#cache-python-dependencies). If you still have questions after reviewing that, consider opening your own question. – sytech Dec 14 '22 at 18:11