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.
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 rspecbefore_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.comstages 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
- deployIf 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
