
Module 3 Lesson 5: Job Control (Rules)
Smart pipelines. Learn how to use 'rules' to decide when a job should run, when it should be manual, and when it should stay hidden.
Module 3 Lesson 5: Job Control (Rules)
You don't always want every job to run.
- You don't want to "Deploy to Production" when you are just fixing a typo in a README.
- You don't want to run expensive "Load Tests" on every tiny commit.
rulesgives you the logic to control your pipeline.
1. The Modern Way: rules
rules is an "If/Then" system for jobs.
deploy-prod:
stage: deploy
script:
- echo "Deploying..."
rules:
# ONLY run if we are on the 'main' branch
- if: $CI_COMMIT_BRANCH == "main"
when: manual # Creates a button you must click!
# Otherwise, do not include this job in the pipeline
- when: never
2. Common Scenarios
A. Run only on Merge Requests
test-mr:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
B. Run when a specific file changes
build-docs:
rules:
- changes:
- docs/**/*
(This is great for saving time; if you only changed code, don't waste time rebuilding the documentation).
3. The allow_failure Key
Sometimes you have a "New" test that is flaky. You don't want it to turn the whole pipeline red.
experimental-test:
script: ./new-tests.sh
allow_failure: true
The job will turn Orange (Warning) if it fails, but the pipeline will still continue to the next stage.
4. only and except (Legacy)
In older tutorials, you will see only: [main] instead of rules.
- Advice: GitLab is moving away from
only/except. Always userulesfor new projects; it is much more powerful and flexible.
Exercise: The Condition Lab
- Create a job
prod-deploythat only runs on themainbranch and ismanual. - Create a job
beta-deploythat only runs on any branch EXCEPTmain. - Modify your README.md. Did the
beta-deployjob run? - Create a "Merge Request" (Pull Request) for your branch. Did the jobs change?
- Why is the
when: manualsetting essential for a "Continuous Delivery" (not deployment) workflow?
Summary
You have completed Module 3: Building Your First Pipeline. You can now pass data, protect secrets, speed up builds with cache, and control exactly when your automation takes action.
Next Module: Pro level: Module 4: Advanced Pipeline Orchestration.