
Module 2 Lesson 3: Jobs, Stages, and Scripts
The workflow triplet. Learn how to group jobs into stages to control their execution order and write effective scripts for your automated tasks.
Module 2 Lesson 3: Jobs, Stages, and Scripts
A pipeline is a journey. To manage this journey, GitLab uses three core concepts: Jobs (What to do), Stages (When to do it), and Scripts (How to do it).
1. Stages (The Timeline)
Stages define the order of execution.
- Jobs in the same stage run in parallel (if you have enough runners).
- Jobs in different stages run sequentially.
stages:
- build
- test
- deploy
If a single job in the build stage fails, the test and deploy stages will never start. This protects your users from bad code.
2. Jobs (The Task)
A job is a named container for your scripts.
- Parallelism: You can have
test-unitandtest-integrationin the samestage: test. They will run at the exact same time, cutting your wait time in half.
Visualizing Jobs and Stages
graph LR
subgraph "Stage: Build"
J1[Job: Compile]
J2[Job: Package]
end
subgraph "Stage: Test"
J3[Job: Unit Tests]
J4[Job: Integration Tests]
end
J1 --> J3
J2 --> J4
3. Scripts (The Action)
The script keyword is just a list of shell commands.
job_name:
script:
- echo "Cleaning up..."
- rm -rf dist/
- npm run build
Pro-Tip: Multi-line Scripts
Instead of a long list of -, you can use the | character for a clean bash block:
job_name:
script: |
if [ "$CI_COMMIT_BRANCH" == "main" ]; then
echo "Deploying to production..."
else
echo "Testing branch..."
fi
4. The before_script and after_script
before_script: Runs before EVERY job. Perfect for logging in to registries or installing dependencies.after_script: Runs after EVERY job, even if the main script fails. Perfect for cleaning up or sending a Slack message.
Exercise: The Pipeline Race
- Create a
.gitlab-ci.ymlwith two stages:morningandevening. - Add a job
wake-upin themorningstage. - Add two jobs in the
eveningstage:eat-dinnerandwatch-tv. - If
wake-upfails (e.g., return code 1), will you get towatch-tv? - If
eat-dinnerfails, willwatch-tvstill run? (Why?) - How would you use
before_scriptto print "Hello World" before every single job?
Summary
Stages are the "Gates" of your software delivery process. By grouping your jobs correctly, you ensure that your computer works as hard as possible (parallelism) while keeping your production environments safe (sequential gating).
Next Lesson: Advanced YAML: Working with YAML in GitLab.