What is difference between script: and before_script: inside a job in gitlab-ci.yml

Viewed 9076

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?

1 Answers

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.

Related