Module 2 Lesson 3: Jobs, Stages, and Scripts
·DevOps

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-unit and test-integration in the same stage: 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

  1. Create a .gitlab-ci.yml with two stages: morning and evening.
  2. Add a job wake-up in the morning stage.
  3. Add two jobs in the evening stage: eat-dinner and watch-tv.
  4. If wake-up fails (e.g., return code 1), will you get to watch-tv?
  5. If eat-dinner fails, will watch-tv still run? (Why?)
  6. How would you use before_script to 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.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn