Operations 5 min read

Understanding GitLab CI/CD Jobs, Scripts, Stages, and Variables

This guide explains how to configure GitLab CI/CD pipelines using the .gitlab-ci.yml file, covering job definitions, script syntax, before_script and after_script hooks, stage ordering, .pre/.post stages, and variable scopes with practical YAML examples.

DevOps Cloud Academy
DevOps Cloud Academy
DevOps Cloud Academy
Understanding GitLab CI/CD Jobs, Scripts, Stages, and Variables

In each project we use a .gitlab-ci.yml YAML file to configure GitLab CI/CD pipelines.

Jobs can be defined with unique names, each containing at least one script. Jobs run independently and can be listed as follows:

job1:
  script: "execute-script-for-job1"
job2:
  script: "execute-script-for-job2"

A simple job example with multiple commands:

job:
  script:
    - uname -a
    - bundle exec rspec

before_script defines commands that run before every job (as an array) and are concatenated with the job's own script in the same shell:

before_script:
  - echo "before-script!!"

after_script defines commands that run after each job (including failed jobs) in a separate shell. It can be defined globally or per‑job, with per‑job definitions overriding the global one:

after_script:
  - echo "after-script"

Global pipeline variables are declared under variables, with job‑level variables taking precedence:

variables:
  DOMAIN: example.com

stages define the order in which jobs run. Jobs in the same stage run in parallel; stages execute sequentially. A typical stage definition looks like:

stages:
  - build
  - test
  - deploy

If stages are not defined, GitLab defaults to build, test, deploy order. Custom stages such as codescan must be placed in the special .pre stage:

codescan:
  stage: .pre
  script:
    - echo "codescan"

The .pre stage always runs first, and .post always runs last; user‑defined stages execute between them.

Each job can specify its own stage to control execution order, for example:

unittest:
  stage: test
  script:
    - echo "run test"

interfacetest:
  stage: test
  script:
    - echo "run test"

Parallel execution may require adjusting the runner's concurrent job limit (default 1, often increased to 10 for faster pipelines).

Overall, the .gitlab-ci.yml file provides a flexible way to define jobs, scripts, hooks, stages, and variables to build robust CI/CD pipelines.

Pipelinegitlab-ci
DevOps Cloud Academy
Written by

DevOps Cloud Academy

Exploring industry DevOps practices and technical expertise.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.